Matlab Codes
Matlab Codes
Creating a Matrix
Use the [] command to create matrix. Separate numbers on the same row by a
comma (i.e. different columns) and create more rows by a semi-column. E.g;
X= [1,2,3;4,5,6;7,8,9] or [[1;4;7],[2;5;8],[3;6;9]] or [[1,2,3];[4,5,6];[7,8,9]]
X(1:4,1:4)=2
This means that starting from 2 increase by 2 until you reach 100
If the interval is negative i.e. a decreasing interval then the second number
representing the interval should carry a negative sign.
Sometimes, it is impossible to generate an interval between 2 points e.g. an interval
between 3 and 10 with an increment of 2. This increment will end at 9. To allow
matlab to automatically determine the spacing interval between 3 and 10 and
space it equally use the function below:
linspace (3,10,5)
3 and 10
zeros (3,5) returns a 3 row by 5 column matrix with all elements been zero
ones (3,5) returns a 3 row by 5 column matrix with all elements been one
Substeting matrices
To subset an element or multiple elements from a matrix A, uss the following
command:
A(row number, column number) A is the name of the matrix [This method
is for single subsetting ]
A(2, [1,3]) This gives the elements in the 2 nd row and in the first and third
columns.
A(2,[1:3]) This gives the elements in the 2nd row from columns 1 to 3
A(2,[1:end]) This gives the elelemts in the 2 nd row, from the 1st column to
the last
A(1:2,1) This gives the elements in row 1 to 2 and column 1
The elements of a matrix that fulfils a certain criteria can be index. E.g.
subset the odd numbers in a matrix A
A(mod(A,2)~=0)
The inner bracket divides every number in A
by 2 and checks if the remainder is not equal to zero. Then the external
bracket sebsets the numbers in the matrix that fulfil this criteria.
All other operations are carried out in the same manner with the functions * /
and +
A.*B
A/B
A./B
A.^C
Raises every element in A to C (if C is a scalar) and raises every
element in A to its corresponding element in C (if C is a matrix)
To sum the elements of a matrix, the sum() function can be used. To sum the
row elements use the following line of code:
Sum(M,1)
a new matrix
Sum(M,2)
TRANSPOSE OF A MATRIX
A
Other functions such as sqrt, sin etc can be performed on matrices once the
matrix is defined and assigned.
Logical Expressions:
Logical operations can be performed between two matrices and a matrix and
a scalar.
If A is a matrix and we want to find out the position of the elements in A that
a greater than C (where C is a scalar); we simply input the line if code:
A>C
This will return a matix with 0s and 1s. The 1s indicate a
true and 0s indicate a false to the logical expression. Matlab takes all the the
eleemts in the matrice and compares them with C. If C is a matrix, Matlab
takes the term in A and compares it with the corresponding term in C.
It is possible to use logical expressions to subset a matrix. Say I want all the
elements in a matrix A that is greater than a number 3. I will simply input the
line of code below:
Y=A(A>3)
Means assign all the elements in the matrix A that are
greater than 3 to a new matrix. The resulting matrix is a column matrix
We can change the elements in A(A>3) to new numbers by the following;
A(A>3)=3
Takes all the elements in A that fulfil the requirements of
the logical expression and change them to the figure 3. After this, the
original matrix is also changed.
CHARACTER ARRAYS
To define a character string, simple embed it in apostrophes as below:
S=Hello
Just like matrix we can joint different character strings together as below:
S=[Hello, ,world]
Displays the words Hello world. The in the
centre is for the space between the hello and world. If it isnt there, the
character will appear as Helloworld.
Sprintf function
Indexing a struct
To index the struct student created above, we type:
Student(1)
this line of code gives you all the information about
student 1. i.e. his class, ID and name.
We can also subset elements of the struct array as below:
Student(1).ID
student only
To subset elements of element of the struct array.e.g. say we want the grade
B of the student as above, then we type
Grades=student(1).grades;
Grades(2)
I can now assign the above struct into a previous struct as below:
Student(1).activities= Myactivities
this
Myactivities struct to the struct student(1).
line
of
code
adds
the
CELL ARRAYS
Cells are created using the {} braces. To create a a 1 by 3 cell, we do the
following.
C={Thomas, 2011, student}
This would create a cell with the
string Thomas, number 2011 and string student
Str2num()
fliplr(A)
to be flipped
NOTE: To return the sine of an angle in degrees use the function sind()
FUNCTIONS
We create functions in matlab by opening the editor file. A function basically
helps you to create a function to perform a specific task. For example if I
want to perform a task a+b, this means that after I create this function, I can
call it anytime like a matlab preinstalled function to perform the addition
task.
E.g. To write a function to sum a and b we write the following line of code:
function [out] = myAdder(a,b)
out = a+b+c;
myAdder is the name of the function and function
is to tell matlab that you are creating a function. Out is the name of the
output. The semicolon at the end of the out command is to prevent matlab
from printing the result to screen immediately.
To comment in front of a code you use the % symbol in front of the code.
To comment a whole block of code, just select the whole code and press
ctrl+r. To un-comment the block of code, select it again and press ctrl+t
You can also write a function with multiple output. E.g as below:
[A,B,C]=mytrigsum(a,b,c)
%sum of cosd(a) and tand(b)
A=cosd(a)+ tand(b);
%sum of A and sind(c);
B=A+sind(c);
%sum of tand(c) and sind(a) and cosd(a);
C=tand(c)+sind(a)+cosd(a) ;
To display the output of the above line of code in the command window, you
type in the following
[A,B,C]=mytrigsum(20,45,60)
20, 45 and 60 represent a, b and
c. you can also define the values to be implemented by the function in the
command window workspace area. E.g.
[A,B,C]=mytrigsum(x,y,z)
where x, y and z must have been
defined in the command window work space. Note I said command window
workspace not function workspace.
SUBFUNCTION
A subfunction is basically a function within a function (i.e. the parent function
needs the function to run). See the line of code below for an example.
function [D] = myDistXYZ(a,b,c)
D(1)=myDist(a,b);
D(2)=myDist(b,c);
D(3)=myDist(a,c);
end
function [D] = myDist(a,b)
D= sqrt((b(1)-a(1))^2 + (b(2)-a(2))^2);
end
The above line of code while implementing the main function myDistXYZ
calls the subfunction myDist. However, unlike writing the code to be
implemented in the parent code only, using the function.
FUNCTION HANDLES
function handles are used to assign the operation of a function to a variable.
E.g.
F=@sind
This assigns the function of sind to the variable F such
that anytime F(x) is entered in the command window it returns the value
sind(x). In other words, F begins to behave like sind.
SCRIPT FILES
Script files are meant for the same lines of code you type in the command
line, however in a script you have the opportunity to change the variables
and obtain different results without having to type all lines of code over and
over again.
It should be noted that the workspace of the command window shares its
workspace memory with the script. This means that if you define a variable
in the script thats already in the command window, this will override the
command window variable.
Chapter 4
IF ELSE STATEMENTS.
If else statement are used to execute matlab codes using logical expressions.
Say example, I want to write a function to diplay whether a thermostat is
heating or not based on its temperature. I can do this using the current
temperature and expected temperature of the thermostat as follows:
function [status] = myThermostat(temp,desired_temp)
if temp > desired_temp +5
status = Heat;
elseif temp < desired_temp 5
status = cool;
else
status = off
end
In the above line of code, the first line defines the output parameters and the
input parameters. Then the rest are as:
If the temperature of the thermostat is greater than the ideal temperature
plus 5 degrees write to screen that the engine is heating. If the temperature
of the thermostat is less than the desired temperature minus 5 degrees then
write to screen that the engine is cold. If none of the above is fulfilled then
write to screen that the engine is off.
More can be introduced into the conditional statements using logicals. E.g.
If x>2 && x<4
if x>2
if y<2
out=x+y;
else
out=x-y;
end
else
if y>2
out=x*y;
else
out=0;
end
end
end
The above statement means that if x is greater than 2, then move to 2 nd line
of code and if y is greater less than 2 do out else do out. However, if x is
less than 2, proceed to 8th line of code and if y is greater excute out else
execute out=0.
It is also possible to use branching statements on input arguments. For
example we want a function that can calculate both the area and
ircumference of a circle. We can use if statement on branching as follows:
ITERATIONS
For loops