ans

advertisement
Introduction to MATLAB basics:
Introduction to Vectors in MATLAB
This is the basic introduction to MATLAB. In this tutorial we cover following topic:
• Defining a vector
• Accessing elements within a vector
• Basic operation on vectors
Defining a vector:
A vector is defined by placing a sequence of numbers with in square braces:
•
>> s=[3 4 5]
s=
3
4
5
This instruction creates a row vector which has the label “s”. It has 3 entries which are
3, 4, 5.
If you don’t want to print the result then put a semi-colon at the end of the line.
•
>> s=[2 3];
>>
This instruction will only save the vector and not display it.
•
>> s
s=
2
3
This instruction is used to view the vector. To view the vector, just type its label. This will
display the vector on the screen.
Row Vector:
We can define a vector of any size by the same method. This instruction will write a row
vector.
•
>> v=[2 4 6 8 78 -58]
v=
2
4
6
8
78 -58
Column Vector:
This instruction written bellow is used to create a column vector. We just take the
transpose of a row vector. The transpose is defined by using an apostrophe.
•
v=[3 1 4 5 8]'
v=
3
1
4
5
8
To Show the Vector of Any Length:
To show the vector of any length of an equal increment we can use the instruction
written bellow. In this instruction the first element shows the first element or value of the
vector or the starting point of the vector. The mid value shows the increment and the
last value gives the last value or the ending point of the vector.
•
>> v = [2:.25:4]
v=
Columns 1 through 5
2.0000
2.2500
2.5000
2.7500
3.0000
Columns 6 through 9
3.2500
3.5000
3.7500
4.0000
To take any Value from the defined vector:
If we wish to take any value from the pre defined vector we can use the instruction given
bellow. This instruction will show the first value of the vector defined above
•
>> v(1)
ans =
2
To write a large vector:
To simplify the creation of large vector, 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, as an example is illustrated above.
•
>> 0:5:25
ans =
0
•
5
10
15
20
25
>> ans'
ans =
0
5
10
15
20
25
To take any last saved result:
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 above. 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 as
above.
If there is a vector defined v=[0:5:25],than it can be retrieved by just writing the name of
that vector.
• >> v = [0:5:25]
v=
0
5
10
15
20
25
5
10
15
20
25
>> v
v=
0
>> v;
>> v'
ans =
0
5
10
15
20
25
Basic Operations On Vectors:
Addition or Subtraction:
To add or subtract the vectors ‘u’ and ‘v’ the instructions will be as follows.
>> v (1:3)-u(2:4)
ans =
-2
-2
-2
To define a new vector with the number from 0 to 4 in steps of -1 we do the following:
>> u= [0:-1:-4]
u=
0
-1
-2
-3
-4
Adding u and v in standard way:
>> u+v
ans =
0
1
2
3
4
Additionally, scalar multiplication is defined in the standard way. Also not that scalar
division is defined in a way that is consistent with scalar multiplication:
Multiplication and Division:
This instruction will multiply the vector “u” defined above with -2.
>> -2*u
ans =
0
2
4
6
8
The instruction written bellow will divide the vector v by 3.
>> v/3
ans =
0
0.6667
1.3333
2.0000
2.6667
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
Multiplication of corresponding elements:
If we define two vectors ‘u’ and ‘v’ where u=[2:3:15] and v=[1:2:9] the element to
element multiplication would be done by the following instructions.
>> v=[1:2:9]
v=
1
3
5
7
9
11
14
>> u=[2:3:15]
u=
2
5
8
15
40
>> u.*v
ans =
2
77 126
Division of corresponding elements:
If we define two vectors ‘u’ and ‘v’ where u=[2:3:15] and v=[1:2:9] the element to
element division would be done by the following instructions.
>> v./u
ans =
0.5000
0.6000
0.6250
0.6364
0.6429
Vector Functions:
In the bellow instruction we will simply define two vectors “u” and “v” and then
manipulate some basic functions on them.
>> v=[1 2 3]'
v=
1
2
3
>> b=[2 4 6]'
b=
2
4
6
>> v+b
ans =
3
6
9
>> v-b
ans =
-1
-2
-3
Multiplication of vectors:
Multiplication of vectors and matrices follows the strict rules. For the multiplication of
vectors there should be the number of columns of second vector equal to the number of
rows of first columns.
For example in this example this condition is not satisfied. So,
>> v*b
??? Error using ==> mtimes
Inner matrix dimensions must agree.
>> v*b'
ans =
2
4
6
4
8
12
6
12
18
>> v'*b
ans =
28
To create other functions:
>> sin(v)
This instruction will take the “sine” of the predefined vector “v”.
ans =
0.8415
0.9093
0.1411
This instruction will take the “log” of the predefined vector “v”.
>> log(v)
ans =
0
0.6931
1.0986
Complex Functions:
>> x=[0:0.1:100]
x=
Columns 1 through 12
0
0.1000
0.2000
0.3000
0.4000
0.5000
0.6000
Columns 997 through 1001
99.6000 99.7000 99.8000 99.9000 100.0000
>> y=sin.*x./(1+cos(x));
Comments on vectors:
1. By this section we can write a vector of any length and of any dimension
according to our requirements.
2. We can implement many functions on the vectors like addition, multiplication and
division.
3. We can recall any element of predefined vector according to our requirements.
4. We can multiply and divide the vectors element to element.
5. We can make any vector of any length with only some instructions.
Plotting A Graph:
To plot a graph of any function we will use the instruction written bellow. Firstly we will
define the function which we want to plot the simply write the instructions written bellow.
>> plot(y)
This instruction will plot the graph of the function “y”.
Example:
We will define the variable ‘x’
>> x=[0:0.1:100];
Then we will define the function ‘y’ against which we wish to plot the function x.
>> y=sin(x).*x./(1+cos(x));
Then we will give the instruction to plot the graph.
>>plot(x,y)
This instruction will plot the graph between ‘x’ and ‘y’
The plotted graph will be as shown in fig.
Figure plot(x,y)
To give Titles:
To give the titles to the plotted figures we will use the following instructions.
Title <title name>
This instruction will give a title name to the figure.
To give name to Axes:
To give the name to any axis we will use the following instructions.
Xlabel <label name>
This instruction wil give the desired name to the x-axis.
Ylabel <lable name>
This instruction will give the name to the y-axis.
Comments on Plotting Graphs:



Using these instructions we can plot a graph of any function.
We can give the names to the axes.
We can change the design of our plotted graph like by changing colors or types
of the graph.
Introduction to Matrices in MATLAB
This portion will contain the following parts.
• Defining Matrices
• Matrices Functions
• Matrices Operation
Defining A Matrix:
Defining a matrix is similar to defining a vector. To define a matrix, you can treat it
like a column row vectors (note that the spaces are required):
>> A =[1 2 3; 3 4 5; 6 7 8]
A=
1
3
6
2
4
7
3
5
8
We 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
7
3
5
8
Matrix Functions:
To find the inverse of any matrix we will use the instructions written bellow.
>> inv(A)
This instruction will show the inverse of the matrix “A” in next line.
ans =
1.0e+015 *
-2.7022 4.5036 -1.8014
5.4043 -9.0072 3.6029
-2.7022 4.5036 -1.8014
To find the Eigen values:
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
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 some operations operated on matrices defined or written bellow.
Division:
These instructions will divide the predefined vector “A” by the vector “v”.
>> v=[1 3 5]'
v=
1
3
5
>> x=A\v
x=
1.0e+015 *
1.8014
-3.6029
1.8014
>> x=B\v
x=
-8.0000
3.0000
1.0000
Multiplication:
>> x=B*v
x=
22
49
64
>> x=v'/B
x=
-8.0000
3.0000
1.0000
X1*B
ans=
1.0000
3.0000
5.0000
Comments on Matrices:
By using these instructions we can
1.
2.
3.
4.
5.
Define any matrix of any dimensions.
Perform many operations to the matrices.
Recall the pre defined matrix.
Multiply and divide the different matrices.
Multiply and divide the elements of any matrix one by one.
To Clear the Page:
Finally, sometimes you would like to clear all of your data and start over. You do this
with the “clear” command. Be careful though, it does not ask you for second opinion and
its results are final.
>> clear
>> whos
Loops
Loop are use when we want to repeat some instructions more than one times without
writing the instructions more than once. There are two loops which are basically used.
1. For Loops
2. While Loops
For Loops
The ‘for’ loop allows us to repeat certain commands, if we want to repeat some action in
a predetermined way, we 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”.
The ‘for loop’ is written around some set of statements, and we must tell MATLAB
where to start and where to end.
Basically, we give a vector in the “for” statement, and MATLAB will loop through for
each value in the vector:
For example, a simple loop will ‘for’ 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 loop” 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 well update the value of “j”
and repeat the statements within the loop.
Example 1:
We define a vector “A” then we will apply a “for loop” on that vector.
>> 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
Now this instruction will subtract the elements of the first row from the second row and
will replace the new elements in the second row. The new “A” vector would be. Then in
the next step it will subtract the elements of the third row from the elements of the
second row.
A=
1
3
2
1
-1
-1
3
1
3
A=
1
3
2
1
-1
-1
2
2
4
Example 2:
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
1
3
2
0
-4
-3
0
-8
-3
B=
Example 3:
Another example where loops come in handy is the approximation of differential
equations. The following example approximates the ‘Differential Equations’ 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 approximaion is found. The approximaion 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;
>> 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)
By plotting this graph we will get the graph as shown in the fig.
>> plot(x,y,'go')
By giving this instruction of plotting the graph we will get.
>> plot (x,y,'go',x,y)
By giving this instruction of plotting the graph we will get.
While loops:
Instead of “for loop” , “while loop” can also b used. The “while loop” repeats a sequence
of commands as long as some condition is met. This can make for more efficient
algorithm.
>> h=0.001;
>> x=[0;h;2];
>> y=0*x;
>> y(1)=1;
>> i=1;
>> size(x)
ans =
3
1
>> max(size(x))
ans =
3
>> while (i<max(size(x)))
y(i+1)=y(i)+h*(x(i)-abs(y(i)));
i=i+1;
end
>> plot(x,y)
Comments:
1. By using the loop instructions we can do any instruction or set of many
instructions at the same time using only one loop defined.
2. We can use “for loop” and “while loop” according to our requirement.
3. “for loop” is used when we know that how much times the loop will run but in
case when we don’t know that how much times the loop will run we use the
“while loop” .
Executable Files:
The MATLAB software provides a full programming language that enables you to write
a series of MATLAB statements into a file and then execute them with a single
command. MATLAB allows you to perform more complex operations and it is easier to
repeat these operations. For this purpose you will need to create the file. The easiest
way is to use the built in MATLAB editor. It will allow you to do some very simple
manipulations. When you write a MATLAB function or script, you save it to a file called
an M-file .
Types of M-files:
There are two types of M-files that you can write:
Scripts:
Ø These are useful for automating a series of steps you need to perform many
times.
Ø They do not accept input arguments and return output arguments.
Ø They store variables in a workspace internal to the function.
Functions:
Ø They are useful for extending the MATLAB language for your application.
Ø They can accept input arguments and return output arguments.
Ø They store variables in a workspace internal to the function.
To get MATLAB to execute the commands in the file simply type in the name of the
file with which you saved it. MATLAB will then search the current directory for the file
and then it will read the file and execute the commands in the file. MATLAB will show an
error if you will type wrong file name.
Example:
For example you have defines two vectors A and B and let A=[1 2 3] and B=[4 5
6] in the MATLAB editor and you have saved it as ‘Variables’ with the M-file extension.
Now whenever U will need these vectors u will just write variables in your command
prompt and the MATLAB will show the values of the variables A and B.
>>
>> Variables
A=
1
B=
2
3
4
5
6
>>
Subroutines:
Sometimes you want to repeat a sequence of commands, but you want to be
able to do so with different vectors and matrices.One way to make this easier is through
the use of subroutines. Subroutines are just like executable files but you can pass it
different vectors and matrices to use.
Data files:
MATLAB does not allow you to save the commands that you have entered in a session,
but it does allow a number of different ways to save the data. We try different ways to
save and read data in this MATLAB tutorial.
1. Saving and recalling data
2. Saving a session as text
3. C Style read or write
Saving and recalling data:
Here we focus on how to save and recall data from MATLAB session. The command to
save all of the data in a session is save. The command to bring data set in data file back
into a session is load. We first look at the Save command.
•
>> u=[1 3 5];
>> v=[2 8 -3];
>> whos
Name
Size
Bytes Class
u
1x3
24 double
v
1x3
24 double
>> save exp1.mat
Attributes
>> ls
.
..
exp1.mat
These instructions are used to save all of the data in the file named “exp1.mat” ( .mat is
the default extension for MATLAB data). Now the values of u and v are saved in the file
exp1.mat
The LS command is used to lit all of the files in the current directory.
•
>> clear
>> whos
>> load exp1.mat
>> whos
Name
Size
Bytes Class
u
1x3
24 double
v
1x3
24 double
Attributes
>> u-v
ans =
-1
-5
8
These instructions are used to read back the data. The data can be read by load
command.
•
>> clear
>> whos
>> load exp1.mat u
>> whos
Name
Size
Bytes Class
Attributes
u
1x3
24 double
>> u
u=
1
3
5
If we don’t want to load all the contents into the memory then after we specify the file
name, we then list the variables which we want to load separated by spaces as we done
in above instructions. By these instructions, we load only the value of u from the file
exp1.mat which contains both u and v in it.
Saving session as text:
These instructions are used for saving a session as a text. We can save a copy of what
happens in a session using the diary command. This is very useful if we want to save
the session for an assignment or as a way to take notes. These instructions create a file
called “save.txt” which will hold an exact copy of the output from the session.
•
>> diary save.txt
>> a=[1 1 3];
>> b=[3 4 2];
>> a+b
ans =
4
5
>> diary
5
Download