Matlab Tutorial Am
Matlab Tutorial Am
Computer Programming
with
MATLAB
A Quick Start
Alireza Maheri
January 2010
PART I-Basics
Editor
Command
Window
Command
Working
line
directory
Arithmetic
Operation Example
Operators
+ Addition a+2
- Subtraction 3.5-45
* Multiply x*y
/ Divide 5/4
^ Power 2^3
Table 1-Arithmetic operators
Operands can be numbers or variables.
Northumbria University, Mechanical Engineering Division © 2010 Alireza Maheri 2
Computer Programming with MATLAB
3. Numbers
Numbers Example
Integer 2, -256
Real 3.5, -45.3e-7
Complex 5-4.5i, 2.1e3-350i ( i 1 )
Inf Number divided by zero
0/0
NaN 0*Inf ,Inf/Inf, inf-inf, -inf+inf
any arithmetic operation on a NaN
Table 2-Numbers
The “e” notation is used for very large or very small numbers: -1.3412e+03
Variables can assume different values. Variables are locations for storing data. Each variable has a unique
name indicating the location of the data. In an assignment statement, a variable appears on the left hand
side (LHS) of the assignment sign, = , and an arithmetic statement on the right hand side (RHS). The
value of the RHS is computed and assigned to the variable on the LHS. Each variable must be assigned a
value before it may be used on the RHS of an assignment statement.
>> a+2
??? Undefined function or variable 'a'.
>> a=3
a =
3
>> b=a+2
b =
5
>> a=10*a+b
a =
35
>> b=2;h=5;I=b*h^3/12
I =
20.8333
Legal names consist of any combination of letters, digits and ‘_’ , starting with a letter.
MaxStress, friction_loss, Y, y, d6f2hA, a_2
You can use the isvarname function to make sure a name is valid before you use it. isvarname
returns 1 if the name is valid, and 0 otherwise.
Example:
isvarname 8th_column
ans =
0 % Not valid - begins with a number
Special names by default are defined in MATLAB. These include pi, i, j (pi= ; i j 1 )
>> 2*pi
ans =
6.2832
>> 5+i
ans =
5.0000 + 1.0000i
>> 3*j
ans =
0 + 3.0000i
5. Operation sequence
Operators precedence:
First: ^
Second: * and /
Third: + and -
In MATLAB arithmetic operation starts from the inner brackets, from left to right, with the above
operator precedence.
1 1
Example 1: Calculate (= 0.0333 ) in MATLAB
5 6 30
>> 1/5*6
ans =
1.2000
1 6
( 6 )
5 5
>> 1/(5*6)
ans =
0.0333
(Correct)
>> 1/5/6
ans =
6. Scalars
>> rem(27,6)
ans =
3
>> round(1.2)
ans =
1
>> round(-4.6)
ans =
-5
>> floor(2.3)
ans =
2
>> floor(-2.3)
ans =
-3
>> ceil(-2.3)
ans =
-2
fix round towards zero
>> fix(-2.3)
ans =
-2
7. Vectors
A vector is a 1xn or nx1 matrix OR one row or one column of another matrix.
Or alternatively
>> a=[5 8 1.2 -7.4 12 45 -3.5]
a =
5.0000 8.0000 1.2000 -7.4000 12.0000 45.0000 -3.5000
>> a=[5 8 0 -7.4];find(a<0) (this statement finds the index of the negative elements)
ans =
4
>> a=[5 8 0 -7.4];find(a>2) (this statement finds the index of the elements greater than 2)
ans =
1 2
>> a=[5 8 0 -7.4];find(a~=8) (this statement finds the index of the elements not equal to 8)
ans =
1 3 4
>> a=[5 8 0 -7.4];find(a>=5) (this statement finds the index of the elements equal or greater than 5)
ans =
1 2
>> a=[5 8 0 -7.4];find(a<=5) (this statement finds the index of the elements equal or less than 5)
ans =
1 3 4
>> a=[5 8 0 -7.4];find(a==1) (this statement finds the index of the elements equal to 1)
ans =
Empty matrix: 1-by-0
Comparisons in MATLAB are performed with the aid of the following operators. Operands can be numbers
or variables.
Comparison
Operation Example
Operators
< Less than a<b
> Greater than a+5>c
== Equal to X==y
<= Less than or equal to 5<=b
>= Greater than or equal to a>=x+2
~= Not equal to Y~=2
Table 3-Comparison operators
Northumbria University, Mechanical Engineering Division © 2010 Alireza Maheri 9
Computer Programming with MATLAB
element-wise subtraction -
>> a=[5 8 0 -7.4];b=[3 2 67 -1];a-b
ans =
2.0000 6.0000 -67.0000 -6.4000
element-wise multiplication .*
>> a=[5 8 0 -7.4];b=[3 2 67 -1];a.*b
ans =
15.0000 16.0000 0 7.4000
element-wise division ./
>> a=[5 8 0 -7.4];b=[3 2 67 -1];a./b
ans =
1.6667 4.0000 0 7.4000
element-wise power .^
>> a=[5 8 0 -7.4 ];b=[3 2 67 -1];a.^b
ans =
125.0000 64.0000 0 -0.1351
In order to perform an element-wise operation both vectors must be row vectors or column vectors and
must have the same length.
Example:
>> a=[5 8 0 -7.4 37];b=[3 2 67 -1];a+b
??? Error using ==> plus
Matrix dimensions must agree.
8. Matrices
8.1. Constructing a matrix in MATLAB
Constructing a matrix by blocks (two or more matrices, vectors, parts of other matrices, etc)
Make sure that size and length of blocks are consistent.
Row vectors
a =
5.0000 8.0000 0 -7.4000
b =
3 2 67 -1
>> m=[a;b]
Northumbria University, Mechanical Engineering Division © 2010 Alireza Maheri 10
Computer Programming with MATLAB
m =
5.0000 8.0000 0 -7.4000
3.0000 2.0000 67.0000 -1.0000
Column vectors
a =
5.0000
8.0000
0
-7.4000
b =
3
2
67
-1
>> m=[a,b]
m =
5.0000 3.0000
8.0000 2.0000
0 67.0000
-7.4000 -1.0000
>> m(2,3)
ans =
9
>> m(2:4,1:3)
ans =
7 6 9
0 25 1
10 -76 -12
>> m(:,3)=[]
m =
2 3 14 -4
7 6 -3 12
0 25 -3 4
>> m(2,:)=[]
m =
2 3 5 14 -4
0 25 1 -3 4
>> m(2:3,:)=[]
m =
2 3 5 14 -4
>> sin(a)
Northumbria University, Mechanical Engineering Division © 2010 Alireza Maheri 12
Computer Programming with MATLAB
ans =
0.8415 0.1411 -0.9589
-0.5366 -0.2794 0.9589
0.9093 -0.1411 0.9906
All vector functions can be used on matrices with the operation taking place column-wise.
Example:
a =
1 3 5
12 6 -5
2 -3 14
>> sort(a)
ans =
1 -3 -5
2 3 5
12 6 14
9.1. Making your first m-file: Writing your first script in MATLAB
Create a new folder. This folder will be your working folder, where you save your m-files.
Change the current directory in MATLAB to your working folder.
Open MATLAB and make a new m-file: in MATLAB: FileNewM-File
In the blank file type the text below and save it with a proper name (e.g. StressInBeams_1).
StressInBeams_1.m
% ================================================
% This script calculates the maximum normal stress in a rectangular cantilever beam
% ================================================
% Parameter definition:
% f: force (N)
% l: beam length (m)
% b: cross section width (m)
% h: cross section height (m)
% max_stress: maximum normal stress (MPa)
% ================================================
f=10000;
l=2;
b=0.05;
h=0.1;
max_stress=6*f*l/b/h^2;%calculate the maximum stress
max_stress=max_stress/1e6 %Convert from Pa to MPa
Now type StressInBeams_1 in command window and press enter. The result will be shown on the
command window:
max_stress =
240.0000
>>
Note 1: MATLAB ignores any statement appear after % sign on a line. These statements are called
“comments” and are implemented by programmer giving information necessary for understanding,
following and editing the program.
Note 2: At the beginning of each program, it is a good practice to clear all variables.
StressInBeams_2.m
% ================================================
% This script calculates the maximum normal stress in a rectangular cantilever beam
% and shows the result only if the beam is safe
% ================================================
% Parameter definition:
% f: force (N)
% l: beam length (m)
% b: cross section width (m)
% h: cross section height (m)
% max_stress: maximum normal stress (MPa)
% all_stress: allowable normal stress (MPa)
% ================================================
f=10000;
l=2;
b=0.05;
h=0.1;
all_stress=300;
max_stress=6*f*l/b/h^2;%calculate the maximum stress
max_stress=max_stress/1e6; %Convert from Pa to MPa
if max_stress < all_stress
max_stress
end
The code shows the value of the max_stress only if it is less than all_stress.
Assume that you want your code compares the maximum and allowable stresses and shows a proper
message (safe/not safe) based on the result of the comparison.
StressInBeams_3.m
% ================================================
% This script calculates the maximum normal stress in a rectangular cantilever beam
% and indicates whether the beam is safe or not
% ================================================
% Parameter definition:
% f: force (N)
% l: beam length (m)
% b: cross section width (m)
% h: cross section height (m)
% max_stress: maximum normal stress (MPa)
% all_stress: allowable normal stress (MPa)
% ================================================
f=10000;
l=2;
b=0.05;
h=0.1;
all_stress=300;
max_stress=6*f*l/b/h^2;
max_stress=max_stress/1e6 %Convert from Pa to MPa
if max_stress < all_stress
'safe'
else
'not-safe'
end
Output
max_stress =
240.0000
ans =
safe
Note: See how we define a string of characters in MATLAB (e.g. 'safe' and 'not-safe')
There are occasions that we want to repeat a series of commands for a specified number of times. In these
cases we can use for statement. Assume that you want to calculate the maximum stress in the beam for a
series of lengths, say l=2 to 4 m with 0.5 m increments.
f=10000;
b=0.05;
h=0.1;
all_stress=300;
for l=2:0.5:4
max_stress=6*f*l/b/h^2;%calculate the maximum stress
max_stress=max_stress/1e6 %Convert from Pa to MPa
if max_stress < all_stress
'safe'
else
'not-safe'
end
end
Result:
max_stress =
240.0000
ans =
safe
max_stress =
300.0000
ans =
safe
max_stress =
360.0000
ans =
not-safe
max_stress =
420.0000
ans =
not-safe
max_stress =
480.0000
ans =
not-safe
>>
f=10000;
b=0.05;
h=0.1;
all_stress=300;
results=[];
for l=2:5 % loop of length
for f=1000:1000:10000 % loop of force
max_stress=6*f*l/b/h^2;%calculate the maximum stress
max_stress=max_stress/1e6; %Convert from Pa to MPa
if max_stress < all_stress
safety=1;
else
safety=0;
end
results=[results; l,f,max_stress,safety];
end
end
results
Output:
results =
2 1000 24 1
2 2000 48 1
2 3000 72 1
2 4000 96 1
2 5000 120 1
2 6000 144 1
2 7000 168 1
2 8000 192 1
2 9000 216 1
2 10000 240 1
3 1000 36 1
3 2000 72 1
3 3000 108 1
3 4000 144 1
3 5000 180 1
3 6000 216 1
3 7000 252 1
3 8000 288 1
3 9000 324 0
3 10000 360 0
4 1000 48 1
4 2000 96 1
4 3000 144 1
4 4000 192 1
4 5000 240 1
Northumbria University, Mechanical Engineering Division © 2010 Alireza Maheri 18
Computer Programming with MATLAB
4 6000 288 1
4 7000 336 0
4 8000 384 0
4 9000 432 0
4 10000 480 0
5 1000 60 1
5 2000 120 1
5 3000 180 1
5 4000 240 1
5 5000 300 1
5 6000 360 0
5 7000 420 0
5 8000 480 0
5 9000 540 0
5 10000 600 0
Note: See how the variable results grows from an empty matrix (results=[];) to a matrix of
the size of 40x4 stores all the information in itself.
Note: An increment of 1 can be omitted from the for statement (for l=2:5 instead of for
l=2:1:5)
Note the application of command format in producing a proper output display.
This command is used when the programmer does not know the number of repeats. A while loop is
terminated when the expression changes from true to false.
Assume you want to find the maximum permissible length of the beam at which the beam is safe under a
load of 3KN.
StressInBeams_6.m
% ================================================
% This script finds the maximum permissible length of cantilever beam at which
% the beam is safe under a load of 3kN
% ================================================
% Parameter definition:
% f: force (N)
% l: beam length (m)
% b: cross section width (m)
% h: cross section height (m)
% max_stress: maximum normal stress (MPa)
f=3000;
b=0.05;
h=0.1;
all_stress=300;
delta_l=0.001; %increment of 1 mm for length
l=0; %initial length of the beam
max_stress=0;%at l=0 max_stress=0
while max_stress<all_stress %repeat the commands within this loop as long as
max_stress< all_stress
l=l+delta_l; %increase the length by 1 mm
max_stress=6*f*l/b/h^2; %calculate the maximum stress
max_stress=max_stress/1e6; %Convert from Pa to MPa
end
l=l-delta_l
Output:
l =
8.333
>>
Push button
Check box Axes
Radio
button
Edit box
There are two ways of generating a GUI in MATLAB: (i) using “GUIDE” a wizard software in
MATLAB and (ii) writing the MATLAB code for the GUI from scratch. By writing the code for GUI
from scratch, the programmer has more control on its function and appearance, although using GUIDE
initially seems easier. Here, you will learn how to write a GUI from scratch.
MyFirstGUI.m
%This script generates a GUI with two edit boxes and one pushbutton
Note:
This script has four statements, one for definition of the main figure and other three for the
components.
Each component has a parent.
Each component has a style and position, defining the type of the component and its location in
the main figure.
In order to get access to the value typed in the force edit box, or display the result on the result edit
box, you need to assign a tag property to each of them. These tags are identifiers.
Northumbria University, Mechanical Engineering Division © 2010 Alireza Maheri 22
Computer Programming with MATLAB
The pushbutton has a callback property. A callback property identifies the function or script,
which will be executed when you click the pushbutton.
If you run MyFirstGUI from command line, you will see the following GUI.
Figure 3-MyFirstGUI
Now you need to modify StressInBeams_6 as explained below and save it as StressInBeams_7. Here you
need to add one statement, to get the value of the force from the respective edit box in the GUI and
another at the bottom of the code to display the calculated maximum permissible length in the associated
edit box on the GUI.
StressInBeams_7.m
% ================================================
% This script finds the maximum permissible length of cantilever beam at which
% the beam is safe under a given load
% ================================================
% Parameter definition:
% f: force (N)
% l: beam length (m)
% b: cross section width (m)
% h: cross section height (m)
% max_stress: maximum normal stress (MPa)
% all_stress: allowable normal stress (MPa)
% ================================================
%The following command firstly finds the object with the tag=force;
%then gets the value of its string (what has been typed in the edit box);
%and finally convert this string to a numeric value
f=str2num(get(findobj('tag','force'),'string'));
b=0.05;
h=0.1;
all_stress=300;
delta_l=0.001; %increment of 1 mm for length
l=0; %initial length of the beam
max_stress=0;%at l=0 max_stress=0
while max_stress<all_stress %repeat the commands within this loop as long as
max_stress< all_stress
l=l+delta_l; %increase the length by 1 mm
max_stress=6*f*l/b/h^2; %calculate the maximum stress
max_stress=max_stress/1e6; %Convert from Pa to MPa
Northumbria University, Mechanical Engineering Division © 2010 Alireza Maheri 23
Computer Programming with MATLAB
end
l=l-delta_l
%The following command firstly finds the object with the tag=result and
%then sets the value of its string to the length calculated above.
%Here l is converted from a number to a string
set(findobj('tag','result'),'string',num2str(l));
Now if you enter a number in the left editbox (assigned for force) and click the pushbutton, script
StressInBeams_7 will be executed, gets the force from GUI, calculates the length and displays the length
on the right GUI.