Monday, September 19, 2011

DC Motor Speed Modeling in Matlab


DC Motor Speed Modeling in Matlab


DC MOTOR MODELLING

A common actuator in control systems is the DC motor. It directly provides rotary motion and, coupled with wheels or drums and cables, can provide transitional motion. The electric circuit of the armature and the free body diagram of the rotor are shown in the following figure:

For this example, we will assume the following values for the physical parameters.

  • moment of inertia of the rotor (J) = 0.01 kg.m^2/s^2
  • damping ratio of the mechanical system (b) = 0.1 Nms
  • electromotive force constant (K=Ke=Kt) = 0.01 Nm/Amp
  • electric resistance (R) = 1 ohm 
  • electric inductance (L) = 0.5 H
  •  input (V): Source Voltage


The motor torque, T, is related to the armature current, i, by a constant factor Kt. The back emf, e, is related to the rotational velocity by the following equations:


In SI units (which we will use), Kt (armature constant) is equal to Ke (motor constant).



Next, we will start to modelling with Newton's law and Kirchoff's law. These laws applied to the motor system give the following equations:




The transfer function of the model is derived as follows:



The denominator and numerator is given by:


MATLAB representation:

J=0.01;
b=0.1;
K=0.01;
R=1;
L=0.5;
num=K;
den=[(J*L) ((J*R)+(L*b)) ((b*R)+K^2)];
motor=tf(num,den);
step(motor,0:0.1:10);
title('Step Response for the Open Loop System');
xlabel('Time in s')
ylabel('Speed in rad/s')
The response of the system as shown in figure:
PID controller Design: 

The PID controller tuning is done manually by changing the Kp, Ki and Kd values. 
J=0.01;
b=0.1;
K=0.01;
R=1;
L=0.5;
num=K;
den=[(J*L) ((J*R)+(L*b)) ((b*R)+K^2)];
motor=tf(num,den);

Kp=100;
Ki=100;
Kd=10;
PID=tf([Kd Kp Ki],[1 0]); 
sys_closed=feedback(PID*motor,1);
step(sys_closed)
title('Closed loop response')

The closed loop response is given by the


Tune the parameters and find out the better response.




Sunday, September 18, 2011

Conditional Control


Conditional Control — if, else, switch

Conditional statements enable you to select at run time which block of code to execute. The simplest conditional statement is an if statement. For example:
% Generate a random number
a = randi(100, 1);

% If it is even, divide by 2
if rem(a, 2) == 0
    disp('a is even')
    b = a/2;
end
if statements can include alternate choices, using the optional keywords elseif or else. For example:
a = randi(100, 1);

if a < 30
    disp('small')
elseif a < 80
    disp('medium')
else
    disp('large')
end
Alternatively, when you want to test for equality against a set of known values, use a switch statement. For example:
[dayNum, dayString] = weekday(date, 'long', 'en_US');

switch dayString
   case 'Monday'
      disp('Start of the work week')
   case 'Tuesday'
      disp('Day 2')
   case 'Wednesday'
      disp('Day 3')
   case 'Thursday'
      disp('Day 4')
   case 'Friday'
      disp('Last day of the work week')
   otherwise
      disp('Weekend!')
end
For both if and switch, MATLAB executes the code corresponding to the first true condition, and then exits the code block. Each conditional statement requires the end keyword.
In general, when you have many possible discrete, known values, switch statements are easier to read than if statements. However, you cannot test for inequality between switch and case values. For example, you cannot implement this type of condition with a switch:
yourNumber = input('Enter a number: ');

if yourNumber < 0
    disp('Negative')
elseif yourNumber > 0
    disp('Positive')
else
    disp('Zero')
end

Array Comparisons in Conditional Statements

It is important to understand how relational operators and if statements work with matrices. When you want to check for equality between two variables, you might use
if A == B, ...
This is valid MATLAB code, and does what you expect when A and B are scalars. But when A and B are matrices, A == B does not test if they are equal, it tests where they are equal; the result is another matrix of 0's and 1's showing element-by-element equality. (In fact, if A and B are not the same size, then A == B is an error.)
A = magic(4);     B = A;     B(1,1) = 0;

A == B
ans =
     0     1     1     1
     1     1     1     1
     1     1     1     1
     1     1     1     1
The proper way to check for equality between two variables is to use the isequal function:
if isequal(A, B), ...
isequal returns a scalar logical value of 1 (representing true) or 0 (false), instead of a matrix, as the expression to be evaluated by the if function. Using the A and B matrices from above, you get
isequal(A, B)
ans = 
    0
Here is another example to emphasize this point. If A and B are scalars, the following program will never reach the "unexpected situation". But for most pairs of matrices, including our magic squares with interchanged columns, none of the matrix conditions A > B, A < B, or A == B is true for all elements and so the else clause is executed:
if A > B
   'greater'
elseif A < B
   'less'
elseif A == B
   'equal'
else
   error('Unexpected situation')
end
Several functions are helpful for reducing the results of matrix comparisons to scalar conditions for use with if, including
isequal
isempty
all
any

Global Variables


Global Variables

If you want more than one function to share a single copy of a variable, simply declare the variable as global in all the functions. Do the same thing at the command line if you want the base workspace to access the variable. The global declaration must occur before the variable is actually used in a function. Although it is not required, using capital letters for the names of global variables helps distinguish them from other variables. For example, create a new function in a file called falling.m:
function h = falling(t)
global GRAVITY
h = 1/2*GRAVITY*t.^2;
Then interactively enter the statements
global GRAVITY
GRAVITY = 32;
y = falling((0:.1:5)');
The two global statements make the value assigned to GRAVITY at the command prompt available inside the function. You can then modify GRAVITY interactively and obtain new solutions without editing any files.

Useful functions and operations in Matlab


Useful functions and operations in Matlab

Using Matlab as a calculator is easy.
Example: Compute 5 sin(2.53-pi)+1/75. In Matlab this is done by simply typing
5*sin(2.5^(3-pi))+1/75
at the prompt. Be careful with parantheses and don't forget to type * whenever you multiply!
Note that Matlab is case sensitive. This means that Matlab knows a difference between letters written as lower and upper case letters. For example, Matlab will understand sin(2) but will not understand Sin(2).
Here is a table of useful operations, functions and constants in Matlab.
Operation, function or constantMatlab
command
+ (addition)+
- (subtraction)-
× (multiplication)*
/ (division)/
|x| (absolute value of x)abs(x)
square root of xsqrt(x)
exexp(x)
ln x (natural log)log(x)
log10 x (base 10 log)log10(x)
sin xsin(x)
cos xcos(x)
tan xtan(x)
cot xcot(x)
arcsin xasin(x)
arccos xacos(x)
arctan xatan(x)
arccot xacot(x)
n! (n factorial)gamma(n+1)
e (2.71828...)exp(1)
 3.14159265...pi
i   (imaginary unit, sqrt(-1))i

Loops in Matlab


LOOPS

In this tutorial we will demonstrate how the for and the while loop are used. First, the for loop is discussed with examples for row operations on matrices and for Euler's Method to approximate an ODE. Following the for loop, a demonstration of the while loop is given. 

For Loops

The for loop allows us to repeat certain commands. If you want to repeat some action in a predetermined way, you can use the for loop. All of the loop structures in matlab are started with a keyword such as "for", or "while" and they all end with the word "end". Another deep thought, eh. The for loop is written around some set of statements, and you must tell Matlab where to start and where to end. Basically, you give a vector in the "for" statement, and Matlab will loop through for each value in the vector: For example, a simple loop will go around four times each time changing a loop variable, j:
>> for j=1:4,
   j
end


j =

     1


j =

     2


j =

     3


j =

     4

>>
When Matlab reads the "for" statement it constructs a vector, [1:4], and j will take on each value within the vector in order. Once Matlab reads the "end" statement, it will execute and repeat the loop. Each time the for statement will update the value of j and repeat the statements within the loop. In this example it will print out the value of j each time. For another example, we define a vector and later change the entries. Here we step though and change each individual entry:
>> v = [1:3:10]

v =

     1     4     7    10

>> for j=1:4,
     v(j) = j;
end
>> v

v =

     1     2     3     4

Note, that this is a simple example and is a nice demonstration to show you how a for loop works. 
A better example, is one in which we want to perform operations on the rows of a matrix. If you want to start at the second row of a matrix and subtract the previous row of the matrix and then repeat this operation on the following rows, a for loop can do this in short order:
>> A = [ [1 2 3]' [3 2 1]' [2 1 3]']

A =

     1     3     2
     2     2     1
     3     1     3

>> B = A;
>> for j=2:3,
    A(j,:) = A(j,:) - A(j-1,:)
end

A =

     1     3     2
     1    -1    -1
     3     1     3


A =

     1     3     2
     1    -1    -1
     2     2     4

For a more realistic example, since we can now use loops and perform row operations on a matrix, Gaussian Elimination can be performed using only two loops and one statement:
>> for j=2:3,
     for i=j:3,
        B(i,:) = B(i,:) - B(j-1,:)*B(i,j-1)/B(j-1,j-1)
     end
   end

B =

     1     3     2
     0    -4    -3
     3     1     3


B =

     1     3     2
     0    -4    -3
     0    -8    -3


B =

     1     3     2
     0    -4    -3
     0     0     3



Another example where loops come in handy is the approximation of differential equations. The following example approximates the D.E. y'=x^2-y^2, y(0)=1, using Euler's Method. First, the step size, h, is defined. Once done, the grid points are found, and an approximation is found. The approximation is simply a vector, y, in which the entry y(j) is the approximation at x(j).
>> h = 0.1;
>> x = [0:h:2];
>> y = 0*x;
>> y(1) = 1;
>> size(x)

ans =

     1    21

>> for i=2:21,
    y(i) = y(i-1) + h*(x(i-1)^2 - y(i-1)^2);
   end
>> plot(x,y)
>> plot(x,y,'go')
>> plot(x,y,'go',x,y)

While Loops

If you don't like the for loop, you can also use a while loop. The while loop repeats a sequence of commands as long as some condition is met. This can make for a more efficient algorithm. In the previous example the number of time steps to make may be much larger than 20. In such a case the for loop can use up a lot of memory just creating the vector used for the index. A better way of implementing the algorithm is to repeat the same operations but only as long as the number of steps taken is below some threshold. In this example the D.E. y'=x-|y|, y(0)=1, is approximated using Euler's Method:
>> h = 0.001;
>> x = [0:h:2];
>> y = 0*x;
>> y(1) = 1;
>> i = 1;
>> size(x)

ans =

           1        2001

>> max(size(x))

ans =

        2001

>> while(i<max(size(x)))
     y(i+1) = y(i) + h*(x(i)-abs(y(i)));
     i = i + 1;                         
   end
>> plot(x,y,'go')

POLYNOMIALS


POLYNOMIALS

In MATLAB, a polynomial is represented by a vector. To create a polynomial in MATLAB, simply enter each coefficient of the polynomial into the vector in descending order. For instance, let's say you have the following polynomial:
To enter this into MATLAB, just enter it as a vector in the following manner
    x = [1 3 -15 -2 9]
    
         x =
              1  3  -15  -2  9
    
MATLAB can interpret a vector of length n+1 as an nth order polynomial. Thus, if your polynomial is missing any coefficients, you must enter zeros in the appropriate place in the vector. For example,
would be represented in MATLAB as:
    y = [1 0 0 0 1]
    
You can find the value of a polynomial using the polyval function. For example, to find the value of the above polynomial at s=2,
    z = polyval([1 0 0 0 1],2)
    
         z =
              17
    
You can also extract the roots of a polynomial. This is useful when you have a high-order polynomial such as
Finding the roots would be as easy as entering the following command;
    roots([1 3 -15 -2 9])
            
    
         ans =
            -5.5745
             2.5836
            -0.7951
             0.7860
    
Let's say you want to multiply two polynomials together. The product of two polynomials is found by taking the convolution of their coefficients. MATLAB's function conv that will do this for you.
    x = [1 2];
    y = [1 4 8];
    z = conv(x,y)
    
         z =
              1  6  16  16
    
Dividing two polynomials is just as easy. The deconv function will return the remainder as well as the result. Let's divide z by y and see if we get x.
    [xx, R] = deconv(z,y)
    
         xx =
              1  2
    
         R =
              0  0  0  0
    
As you can see, this is just the polynomial/vector x from before. If y had not gone into z evenly, the remainder vector would have been something other than zero.

Plots in Matlab


Plots:
It is also easy to create plots in MATLAB.
y = f(x), and then plot the set points (xi, yi). By default matlab draws a straight line connecting neighboring points, The basic method for plotting a function f(x) in matlab is to create an array of x values, calculate a second array while the points themselves are invisible.
x1 = [0:0.25:4*pi]; % creates an array from 0 to 4*pi with a spacing of 0.25
x2 = linspace(0,4*pi,1000); % creates an array from 0 to 4*pi with 1000 evenly spaced points
y1 = 5*sin(x1).*cos(x1).^2; % calculate y = f(x)
y2 = 5*sin(x2).*cos(x2).^2; % note the use of the element-by-element operations .* .^ ./
plot(x1,y1);
hold on;
plot(x2,y2,’color’,’g’,’LineStyle’,’--’),’LineWidth’,2);
hold off;


Matrices in Matlab


Matrices in Matlab
Defining a matrix is similar to defining a vector. To define a matrix, you can treat it like a column of row vectors (note that the spaces are required!):
>> A = [ 1 2 3; 3 4 5; 6 7 8] A = 1 2 3 3 4 5 6 7 8
You can also treat it like a row of column vectors:
>> B = [ [1 2 3]' [2 4 7]' [3 5 8]'] B = 1 2 3 2 4 5 3 7 8
(Again, it is important to include the spaces.) If you have been putting in variables through this and the tutorial on vectors, then you probably have a lot of variables defined. If you lose track of what variables you have defined, the whos command will let you know all of the variables you have in your work space.
>> whos Name Size Bytes Class A 3x3 72 double array B 3x3 72 double array v 1x5 40 double array Grand total is 23 elements using 184 bytes
We assume that you are doing this tutorial after completing the previous tutorial. The vector v was defined in the previous tutorial. As mentioned before, the notation used by Matlab is the standard linear algebra notation you should have seen before. Matrix-vector multiplication can be easily done. You have to be careful, though, your matrices and vectors have to have the right size!
>> v = [0:2:8] v = 0 2 4 6 8 >> A*v(1:3) ??? Error using ==> * Inner matrix dimensions must agree. >> A*v(1:3)' ans = 16 28 46
Get used to seeing that particular error message! Once you start throwing matrices and vectors around, it is easy to forget the sizes of the things you have created. You can work with different parts of a matrix, just as you can with vectors. Again, you have to be careful to make sure that the operation is legal.
>> A(1:2,3:4) ??? Index exceeds matrix dimensions. >> A(1:2,2:3) ans = 2 3 4 5 >> A(1:2,2:3)' ans = 2 4 3 5

Matrix Functions

Once you are able to create and manipulate a matrix, you can perform many standard operations on it. For example, you can find the inverse of a matrix. You must be careful, however, since the operations are numerical manipulations done on digital computers. In the example, the matrix A is not a full matrix, but matlab's inverse routine will still return a matrix.
>> inv(A) Warning: Matrix is close to singular or badly scaled. Results may be inaccurate. RCOND = 4.565062e-18 ans = 1.0e+15 * -2.7022 4.5036 -1.8014 5.4043 -9.0072 3.6029 -2.7022 4.5036 -1.8014
By the way, Matlab is case sensitive. This is another potential source of problems when you start building complicated algorithms.
>> inv(a) ??? Undefined function or variable a.
Other operations include finding an approximation to the eigen values of a matrix. There are two versions of this routine, one just finds the eigen values, the other finds both the eigen values and the eigen vectors. If you forget which one is which, you can get more information by typing help eig at the matlab prompt.
>> eig(A) ans = 14.0664 -1.0664 0.0000 >> [v,e] = eig(A) v = -0.2656 0.7444 -0.4082 -0.4912 0.1907 0.8165 -0.8295 -0.6399 -0.4082 e = 14.0664 0 0 0 -1.0664 0 0 0 0.0000 >> diag(e) ans = 14.0664 -1.0664 0.0000

Matrix Operations

There are also routines that let you find solutions to equations. For example, if Ax=b and you want to find x, a slow way to find x is to simply invert A and perform a left multiply on both sides (more on that later). It turns out that there are more efficient and more stable methods to do this (L/U decomposition with pivoting, for example). Matlab has special commands that will do this for you. Before finding the approximations to linear systems, it is important to remember that if A and B are both matrices, then AB is not necessarily equal to BA. To distinguish the difference between solving systems that have a right or left multiply, Matlab uses two different operators, "/" and "\". Examples of their use are given below. It is left as an exercise for you to figure out which one is doing what.
>> v = [1 3 5]' v = 1 3 5 >> x = A\v Warning: Matrix is close to singular or badly scaled. Results may be inaccurate. RCOND = 4.565062e-18 x = 1.0e+15 * 1.8014 -3.6029 1.8014 >> x = B\v x = 2 1 -1 >> B*x ans = 1 3 5 >> x1 = v'/B x1 = 4.0000 -3.0000 1.0000 >> x1*B ans = 1.0000 3.0000 5.0000

VECTORS IN MATLAB


VECTORS IN MATLAB

Matlab is a software package that makes it easier for you to enter matrices and vectors, and manipulate them. The interface follows a language that is designed to look a lot like the notation use in linear algebra. In the following tutorial, we will discuss some of the basics of working with vectors.

Almost all of Matlab's basic commands revolve around the use of vectors. A vector is defined by placing a sequence of numbers within square braces:
>> v = [3 1]

v =

     3     1

This creates a row vector which has the label "v". The first entry in the vector is a 3 and the second entry is a 1. Note that matlab printed out a copy of the vector after you hit the enter key. If you do not want to print out the result put a semi-colon at the end of the line:
>> v = [3 1];
>>
If you want to view the vector just type its label:
>> v 

v =

     3     1

You can define a vector of any size in this manner:
>> v = [3 1 7 -21 5 6]

v =

     3     1    7    -21    5    6

Notice, though, that this always creates a row vector. If you want to create a column vector you need to take the transpose of a row vector. The transpose is defined using an apostrophe ("'"):
>> v = [3 1 7 -21 5 6]'

v =

     3
     1
     7
   -21
     5
     6

A common task is to create a large vector with numbers that fit a repetitive pattern. Matlab can define a set of numbers with a common increment using colons. For example, to define a vector whose first entry is 1, the second entry is 2, the third is three, up to 8 you enter the following:
>> v = = [1:8]

v =

     1     2     3     4     5     6     7     8

If you wish to use an increment other than one that you have to define the start number, the value of the increment, and the last number. For example, to define a vector that starts with 2 and ends in 4 with steps of .25 you enter the following:
>> v = [2:.25:4]

v =

  Columns 1 through 7

    2.0000    2.2500    2.5000    2.7500    3.0000    3.2500    3.5000

  Columns 8 through 9

    3.7500    4.0000

Accessing elements within a vector

You can view individual entries in this vector. For example to view the first entry just type in the following:
>> v(1)

ans =

     2

This command prints out entry 1 in the vector. Also notice that a new variable called ans has been created. Any time you perform an action that does not include an assignment matlab will put the label anson the result.
To simplify the creation of large vectors, you can define a vector by specifying the first entry, an increment, and the last entry. Matlab will automatically figure out how many entries you need and their values. For example, to create a vector whose entries are 0, 2, 4, 6, and 8, you can type in the following line:
>> 0:2:8

ans =

     0     2     4     6     8

Matlab also keeps track of the last result. In the previous example, a variable "ans" is created. To look at the transpose of the previous result, enter the following:
>> ans'

ans =

     0
     2
     4
     6
     8

To be able to keep track of the vectors you create, you can give them names. For example, a row vector v can be created:
>> v = [0:2:8]

v =

     0     2     4     6     8

>> v

v =

     0     2     4     6     8

>> v;
>> v'

ans =

     0
     2
     4
     6
     8



Note that in the previous example, if you end the line with a semi-colon, the result is not displayed. This will come in handy later when you want to use Matlab to work with very large systems of equations.
Matlab will allow you to look at specific parts of the vector. If you want to only look at the first three entries in a vector you can use the same notation you used to create the vector:
>> v(1:3)

ans =

     0     2     4

>> v(1:2:4)

ans =

     0     4

>> v(1:2:4)'

ans =

     0
     4

Basic operations on vectors

Once you master the notation you are free to perform other operations:
>> v(1:3)-v(2:4)

ans =

    -2    -2    -2

For the most part Matlab follows the standard notation used in linear algebra. We will see later that there are some extensions to make some operations easier. For now, though, both addition subtraction are defined in the standard way. For example, to define a new vector with the numbers from 0 to -4 in steps of -1 we do the following:
>> u = [0:-1:4]
u = [0:-1:-4]

u =

     0    -1    -2    -3    -4
We can now add u and v together in the standard way:
>> u+v

ans =

     0     1     2     3     4


Additionally, scalar multiplication is defined in the standard way. Also note that scalar division is defined in a way that is consistent with scalar multiplication:
>> -2*u

ans =

     0     2     4     6     8

>> v/3

ans =

         0    0.6667    1.3333    2.0000    2.6667


With these definitions linear combinations of vectors can be easily defined and the basic operations combined:
>> -2*u+v/3

ans =

         0    2.6667    5.3333    8.0000   10.6667


You will need to be careful. These operations can only be carried out when the dimensions of the vectors allow it. You will likely get used to seeing the following error message which follows from adding two vectors whose dimensions are different:

>> u+v'
??? Error using ==> plus
Matrix dimensions must agree.

Matlab: Basics


VECTORS IN MATLAB

Matlab is a software package that makes it easier for you to enter matrices and vectors, and manipulate them. The interface follows a language that is designed to look a lot like the notation use in linear algebra. In the following tutorial, we will discuss some of the basics of working with vectors.

Almost all of Matlab's basic commands revolve around the use of vectors. A vector is defined by placing a sequence of numbers within square braces:
>> v = [3 1]

v =

     3     1

This creates a row vector which has the label "v". The first entry in the vector is a 3 and the second entry is a 1. Note that matlab printed out a copy of the vector after you hit the enter key. If you do not want to print out the result put a semi-colon at the end of the line:
>> v = [3 1];
>>
If you want to view the vector just type its label:
>> v 

v =

     3     1

You can define a vector of any size in this manner:
>> v = [3 1 7 -21 5 6]

v =

     3     1    7    -21    5    6

Notice, though, that this always creates a row vector. If you want to create a column vector you need to take the transpose of a row vector. The transpose is defined using an apostrophe ("'"):
>> v = [3 1 7 -21 5 6]'

v =

     3
     1
     7
   -21
     5
     6

A common task is to create a large vector with numbers that fit a repetitive pattern. Matlab can define a set of numbers with a common increment using colons. For example, to define a vector whose first entry is 1, the second entry is 2, the third is three, up to 8 you enter the following:
>> v = = [1:8]

v =

     1     2     3     4     5     6     7     8

If you wish to use an increment other than one that you have to define the start number, the value of the increment, and the last number. For example, to define a vector that starts with 2 and ends in 4 with steps of .25 you enter the following:
>> v = [2:.25:4]

v =

  Columns 1 through 7

    2.0000    2.2500    2.5000    2.7500    3.0000    3.2500    3.5000

  Columns 8 through 9

    3.7500    4.0000

Accessing elements within a vector

You can view individual entries in this vector. For example to view the first entry just type in the following:
>> v(1)

ans =

     2

This command prints out entry 1 in the vector. Also notice that a new variable called ans has been created. Any time you perform an action that does not include an assignment matlab will put the label anson the result.
To simplify the creation of large vectors, you can define a vector by specifying the first entry, an increment, and the last entry. Matlab will automatically figure out how many entries you need and their values. For example, to create a vector whose entries are 0, 2, 4, 6, and 8, you can type in the following line:
>> 0:2:8

ans =

     0     2     4     6     8

Matlab also keeps track of the last result. In the previous example, a variable "ans" is created. To look at the transpose of the previous result, enter the following:
>> ans'

ans =

     0
     2
     4
     6
     8

To be able to keep track of the vectors you create, you can give them names. For example, a row vector v can be created:
>> v = [0:2:8]

v =

     0     2     4     6     8

>> v

v =

     0     2     4     6     8

>> v;
>> v'

ans =

     0
     2
     4
     6
     8



Note that in the previous example, if you end the line with a semi-colon, the result is not displayed. This will come in handy later when you want to use Matlab to work with very large systems of equations.
Matlab will allow you to look at specific parts of the vector. If you want to only look at the first three entries in a vector you can use the same notation you used to create the vector:
>> v(1:3)

ans =

     0     2     4

>> v(1:2:4)

ans =

     0     4

>> v(1:2:4)'

ans =

     0
     4

Basic operations on vectors

Once you master the notation you are free to perform other operations:
>> v(1:3)-v(2:4)

ans =

    -2    -2    -2

For the most part Matlab follows the standard notation used in linear algebra. We will see later that there are some extensions to make some operations easier. For now, though, both addition subtraction are defined in the standard way. For example, to define a new vector with the numbers from 0 to -4 in steps of -1 we do the following:
>> u = [0:-1:4]
u = [0:-1:-4]

u =

     0    -1    -2    -3    -4
We can now add u and v together in the standard way:
>> u+v

ans =

     0     1     2     3     4


Additionally, scalar multiplication is defined in the standard way. Also note that scalar division is defined in a way that is consistent with scalar multiplication:
>> -2*u

ans =

     0     2     4     6     8

>> v/3

ans =

         0    0.6667    1.3333    2.0000    2.6667


With these definitions linear combinations of vectors can be easily defined and the basic operations combined:
>> -2*u+v/3

ans =

         0    2.6667    5.3333    8.0000   10.6667


You will need to be careful. These operations can only be carried out when the dimensions of the vectors allow it. You will likely get used to seeing the following error message which follows from adding two vectors whose dimensions are different:

>> u+v'
??? Error using ==> plus
Matrix dimensions must agree.

Matrices in Matlab
Defining a matrix is similar to defining a vector. To define a matrix, you can treat it like a column of row vectors (note that the spaces are required!):
>> A = [ 1 2 3; 3 4 5; 6 7 8] A = 1 2 3 3 4 5 6 7 8
You can also treat it like a row of column vectors:
>> B = [ [1 2 3]' [2 4 7]' [3 5 8]'] B = 1 2 3 2 4 5 3 7 8
(Again, it is important to include the spaces.) If you have been putting in variables through this and the tutorial on vectors, then you probably have a lot of variables defined. If you lose track of what variables you have defined, the whos command will let you know all of the variables you have in your work space.
>> whos Name Size Bytes Class A 3x3 72 double array B 3x3 72 double array v 1x5 40 double array Grand total is 23 elements using 184 bytes
We assume that you are doing this tutorial after completing the previous tutorial. The vector v was defined in the previous tutorial. As mentioned before, the notation used by Matlab is the standard linear algebra notation you should have seen before. Matrix-vector multiplication can be easily done. You have to be careful, though, your matrices and vectors have to have the right size!
>> v = [0:2:8] v = 0 2 4 6 8 >> A*v(1:3) ??? Error using ==> * Inner matrix dimensions must agree. >> A*v(1:3)' ans = 16 28 46
Get used to seeing that particular error message! Once you start throwing matrices and vectors around, it is easy to forget the sizes of the things you have created. You can work with different parts of a matrix, just as you can with vectors. Again, you have to be careful to make sure that the operation is legal.
>> A(1:2,3:4) ??? Index exceeds matrix dimensions. >> A(1:2,2:3) ans = 2 3 4 5 >> A(1:2,2:3)' ans = 2 4 3 5

Matrix Functions

Once you are able to create and manipulate a matrix, you can perform many standard operations on it. For example, you can find the inverse of a matrix. You must be careful, however, since the operations are numerical manipulations done on digital computers. In the example, the matrix A is not a full matrix, but matlab's inverse routine will still return a matrix.
>> inv(A) Warning: Matrix is close to singular or badly scaled. Results may be inaccurate. RCOND = 4.565062e-18 ans = 1.0e+15 * -2.7022 4.5036 -1.8014 5.4043 -9.0072 3.6029 -2.7022 4.5036 -1.8014
By the way, Matlab is case sensitive. This is another potential source of problems when you start building complicated algorithms.
>> inv(a) ??? Undefined function or variable a.
Other operations include finding an approximation to the eigen values of a matrix. There are two versions of this routine, one just finds the eigen values, the other finds both the eigen values and the eigen vectors. If you forget which one is which, you can get more information by typing help eig at the matlab prompt.
>> eig(A) ans = 14.0664 -1.0664 0.0000 >> [v,e] = eig(A) v = -0.2656 0.7444 -0.4082 -0.4912 0.1907 0.8165 -0.8295 -0.6399 -0.4082 e = 14.0664 0 0 0 -1.0664 0 0 0 0.0000 >> diag(e) ans = 14.0664 -1.0664 0.0000

Matrix Operations

There are also routines that let you find solutions to equations. For example, if Ax=b and you want to find x, a slow way to find x is to simply invert A and perform a left multiply on both sides (more on that later). It turns out that there are more efficient and more stable methods to do this (L/U decomposition with pivoting, for example). Matlab has special commands that will do this for you. Before finding the approximations to linear systems, it is important to remember that if A and B are both matrices, then AB is not necessarily equal to BA. To distinguish the difference between solving systems that have a right or left multiply, Matlab uses two different operators, "/" and "\". Examples of their use are given below. It is left as an exercise for you to figure out which one is doing what.
>> v = [1 3 5]' v = 1 3 5 >> x = A\v Warning: Matrix is close to singular or badly scaled. Results may be inaccurate. RCOND = 4.565062e-18 x = 1.0e+15 * 1.8014 -3.6029 1.8014 >> x = B\v x = 2 1 -1 >> B*x ans = 1 3 5 >> x1 = v'/B x1 = 4.0000 -3.0000 1.0000 >> x1*B ans = 1.0000 3.0000 5.0000
Plots:
It is also easy to create plots in MATLAB.
y = f(x), and then plot the set points (xi, yi). By default matlab draws a straight line connecting neighboring points, The basic method for plotting a function f(x) in matlab is to create an array of x values, calculate a second array while the points themselves are invisible.
x1 = [0:0.25:4*pi]; % creates an array from 0 to 4*pi with a spacing of 0.25
x2 = linspace(0,4*pi,1000); % creates an array from 0 to 4*pi with 1000 evenly spaced points
y1 = 5*sin(x1).*cos(x1).^2; % calculate y = f(x)
y2 = 5*sin(x2).*cos(x2).^2; % note the use of the element-by-element operations .* .^ ./
plot(x1,y1);
hold on;
plot(x2,y2,’color’,’g’,’LineStyle’,’--’),’LineWidth’,2);
hold off;


POLYNOMIALS

In MATLAB, a polynomial is represented by a vector. To create a polynomial in MATLAB, simply enter each coefficient of the polynomial into the vector in descending order. For instance, let's say you have the following polynomial:
To enter this into MATLAB, just enter it as a vector in the following manner
    x = [1 3 -15 -2 9]
    
         x =
              1  3  -15  -2  9
    
MATLAB can interpret a vector of length n+1 as an nth order polynomial. Thus, if your polynomial is missing any coefficients, you must enter zeros in the appropriate place in the vector. For example,
would be represented in MATLAB as:
    y = [1 0 0 0 1]
    
You can find the value of a polynomial using the polyval function. For example, to find the value of the above polynomial at s=2,
    z = polyval([1 0 0 0 1],2)
    
         z =
              17
    
You can also extract the roots of a polynomial. This is useful when you have a high-order polynomial such as
Finding the roots would be as easy as entering the following command;
    roots([1 3 -15 -2 9])
            
    
         ans =
            -5.5745
             2.5836
            -0.7951
             0.7860
    
Let's say you want to multiply two polynomials together. The product of two polynomials is found by taking the convolution of their coefficients. MATLAB's function conv that will do this for you.
    x = [1 2];
    y = [1 4 8];
    z = conv(x,y)
    
         z =
              1  6  16  16
    
Dividing two polynomials is just as easy. The deconv function will return the remainder as well as the result. Let's divide z by y and see if we get x.
    [xx, R] = deconv(z,y)
    
         xx =
              1  2
    
         R =
              0  0  0  0
    
As you can see, this is just the polynomial/vector x from before. If y had not gone into z evenly, the remainder vector would have been something other than zero.

LOOPS

In this tutorial we will demonstrate how the for and the while loop are used. First, the for loop is discussed with examples for row operations on matrices and for Euler's Method to approximate an ODE. Following the for loop, a demonstration of the while loop is given. 

For Loops

The for loop allows us to repeat certain commands. If you want to repeat some action in a predetermined way, you can use the for loop. All of the loop structures in matlab are started with a keyword such as "for", or "while" and they all end with the word "end". Another deep thought, eh. The for loop is written around some set of statements, and you must tell Matlab where to start and where to end. Basically, you give a vector in the "for" statement, and Matlab will loop through for each value in the vector: For example, a simple loop will go around four times each time changing a loop variable, j:
>> for j=1:4,
   j
end


j =

     1


j =

     2


j =

     3


j =

     4

>>
When Matlab reads the "for" statement it constructs a vector, [1:4], and j will take on each value within the vector in order. Once Matlab reads the "end" statement, it will execute and repeat the loop. Each time the for statement will update the value of j and repeat the statements within the loop. In this example it will print out the value of j each time. For another example, we define a vector and later change the entries. Here we step though and change each individual entry:
>> v = [1:3:10]

v =

     1     4     7    10

>> for j=1:4,
     v(j) = j;
end
>> v

v =

     1     2     3     4

Note, that this is a simple example and is a nice demonstration to show you how a for loop works. 
A better example, is one in which we want to perform operations on the rows of a matrix. If you want to start at the second row of a matrix and subtract the previous row of the matrix and then repeat this operation on the following rows, a for loop can do this in short order:
>> A = [ [1 2 3]' [3 2 1]' [2 1 3]']

A =

     1     3     2
     2     2     1
     3     1     3

>> B = A;
>> for j=2:3,
    A(j,:) = A(j,:) - A(j-1,:)
end

A =

     1     3     2
     1    -1    -1
     3     1     3


A =

     1     3     2
     1    -1    -1
     2     2     4

For a more realistic example, since we can now use loops and perform row operations on a matrix, Gaussian Elimination can be performed using only two loops and one statement:
>> for j=2:3,
     for i=j:3,
        B(i,:) = B(i,:) - B(j-1,:)*B(i,j-1)/B(j-1,j-1)
     end
   end

B =

     1     3     2
     0    -4    -3
     3     1     3


B =

     1     3     2
     0    -4    -3
     0    -8    -3


B =

     1     3     2
     0    -4    -3
     0     0     3



Another example where loops come in handy is the approximation of differential equations. The following example approximates the D.E. y'=x^2-y^2, y(0)=1, using Euler's Method. First, the step size, h, is defined. Once done, the grid points are found, and an approximation is found. The approximation is simply a vector, y, in which the entry y(j) is the approximation at x(j).
>> h = 0.1;
>> x = [0:h:2];
>> y = 0*x;
>> y(1) = 1;
>> size(x)

ans =

     1    21

>> for i=2:21,
    y(i) = y(i-1) + h*(x(i-1)^2 - y(i-1)^2);
   end
>> plot(x,y)
>> plot(x,y,'go')
>> plot(x,y,'go',x,y)

While Loops

If you don't like the for loop, you can also use a while loop. The while loop repeats a sequence of commands as long as some condition is met. This can make for a more efficient algorithm. In the previous example the number of time steps to make may be much larger than 20. In such a case the for loop can use up a lot of memory just creating the vector used for the index. A better way of implementing the algorithm is to repeat the same operations but only as long as the number of steps taken is below some threshold. In this example the D.E. y'=x-|y|, y(0)=1, is approximated using Euler's Method:
>> h = 0.001;
>> x = [0:h:2];
>> y = 0*x;
>> y(1) = 1;
>> i = 1;
>> size(x)

ans =

           1        2001

>> max(size(x))

ans =

        2001

>> while(i<max(size(x)))
     y(i+1) = y(i) + h*(x(i)-abs(y(i)));
     i = i + 1;                         
   end
>> plot(x,y,'go')