You are on page 1of 12

1.

To prevent overwriting existing functions or variable in matlab memory, do


not store any value in such functions. E.g. sin = 2 will store 2 in sin and sin
will no longer return the sine of an angle
Functions
clc clear the screen
clear x will clear the variable defined as x
clear all clears all the defined variable in the present matlab window

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

Creates a 4 by 4 matrice with all elelemts being 2

Class () To check the class of a function


size () To know the size of a matrix (the first number is the row size and
the second is the column size)
size (M,1) display the number of rows only in a matrix M
size (M,2) displays the number of columns only in a matrix M
length () displays the number of elements in one dimensional matrix.

To create an array of number following a repetitive interval say 2 to 100 at an


interval of 2. We type:
[2:2:100]

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

i.e. give me five equally spaced intervals between

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

ASSIGNING AN INDEX TO AN EXISTING MATRIX


You can assign an index to an existing matrix. Say we have a
matrix A with some elements, we can define a new array to
replace some of the elements in the matrix as follows:
A(1,[2,3])=[4,6]
This means the elements in position 1,2 and 1,3
should be replaced with the numbes 4 and 6.

CREATING A MATRIX USING INDEX FORMAT


A matrix can be created using the indexing function and assignment
operator as follows;
A(1,1)=2;
A(1,2)=4;
A(1,3)=5
The above line of codes will create a 1 by 3 matrix of (2 4 5). The semicolons
are used to prevent outputting to the screen.
SELECTING ELEMENTS OF A MATRIX THAT FULFIL A CRITERIA

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.

ARITHMETIC OPERATIONS BETWEEN SCALARS AND ARRAYS


In matlab, the operations between scalars and arrays are carried out element
wise i.e. each element of the array or matrix is multiplied, added, divided by
the scalar. To perform this task we use the line of code
M-2

where M is matrix and 2 is the scalar

All other operations are carried out in the same manner with the functions * /
and +

ARITHMETIC OPERATIONS BETWEEN ARRAY AND ARRAY


Matrix operation in addition and subtraction is the same as in scalar and
array. The number of elements in the both matrices must be the same for
each element of each matrix to be subtracted or added to each other.
For multiplication and division, matlab has two types. The element by
element multiplication and normal multiplication operation in linear algebra.
A*B

Gives the linear algebra matrix operation.

A.*B

Gives element by element multiplication

A/B

Gives linear algebra division operation

A./B

Gives element by element division

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

Gives the sum of the columns that make up the matrix in

Sum(M,2)

Gives the sum of the rows that make up the matrice.

TRANSPOSE OF A MATRIX
A

is the transpose of 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

The character Hello is assigned to the variable S

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

Sprintf(my name is %s, timmy)


This will display the output
my name is timmy. This helps because instead of typing the whole
command line again, the name can be changed to any new name.
Note that the s in the %s stands for string. There are %d for integers
numbers and %f or %g for numbers.
Both %s and %d can be used in a single sprint() function as below:
Class=sprintf(The number of %s in my class is now %d, pupils, 47)
%s will be replaced by pupils and %d by 47.
Struct Arrays
Struct Arrays are used to store both numeric data as in interger or char data
type in a structured manner. Example;
Student(1).class= Primary one;
Student(1).ID= 6639;
Student(1).name= Thomas Oluwafemi;
Student(1).grades= [A, B, C, D, F];
When the term student is typed in the matlab command window, it displays
the property of the struct and what it contains. For this, it will be a 1 x 3
struct.
To index (or subset) a particular information in the struct say name, we
simple type:
Student(1).name
student 1

This line of code gives us the name of the

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

this line of code will return the ID of the

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)

this will return the grade B

Adding new structs to existing structs


New structs can be added to existing structs by first creating the new structs
and then using the assignment operator. E.g.
Myactivities.afterschool= play football
Myactivities.atnight= watch movies

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

Generating random numbers between 0 and 1


To generate a set of randomly distributed number in a matrix, use the
following line of code
rand(5)
This will give you a 5 by 5 matrix containing
elements that are ramdom numbers between 0 and 1
rand(10,20)
This will give you a 10 by 20 matrice containing
randomly generated numbers between 0 and 1

Changing a string to a struct array

Str2num()

Flipping a row of numbers from last to first


If you have a row of numbers assigned A and you want to flip the numbers
froom lst to first use the following line of code

fliplr(A)
to be flipped

Where A is the name assigned to the set of numbers

TO compare if two arrays are equal use the:


A==B
Compares the numerical values of A and B and
returns a 1 or 0 denoting whether it is true or false in logical expression
terms

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.

To display the result from your function in a matrix manner, instead of


individual doubles, write the code as follows:
function [B] = mySqrt(a,b,c)
B(1)=sqrt(a+b+c);
B(2)=sqrt(a-b-c);
end

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

This means if x is greater than but less than 4

NESTED IF ELSE STATEMENTS


It is possible to create if-else statements in a nested form i.e. an if-else
statement in another if-else statement. E.g.

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:

function [out] = myNest(r,calc)


if strcmp(calc, 'area')
out=pi*r.^2;
elseif strcmp(calc,'circumference')
out=2*pi*r
end
end
what the above line of code does is as follows:
once the value of r and calc are entered, the strcmp() function checks

whether the string entered is area. If it is, it implements out=pi*r.^2


if the aforesaid is not obeyed then it checks if the string circumference
is entered and implements out=2*pi*r . if none of the above string is
entered then it will return an error.
Checking the input to a function
It is possible to use if statements in a function or script to check if the input
arguments meet certain requirements. E.g. say a function is written for the input
augments to be strictly doubles, then it is possible to add an if-else statement in the
code block such that if an input argument that is not a double is entered, an error
message is displayed. E.g.

ITERATIONS
For loops

You might also like