Matlab Tutorial Am

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 24

Computer Programming with MATLAB

Computer Programming
with
MATLAB
A Quick Start

Alireza Maheri

Mechanical Engineering Division


School of Computing, Engineering and Information Sciences
Northumbria University

January 2010

Northumbria University, Mechanical Engineering Division © 2010 Alireza Maheri 1


Computer Programming with MATLAB

PART I-Basics

1. MATLAB a Calculator; MATLAB a Programming Environment


MATLAB can be used both as a programming environment and as a scientific calculator. To use
MATLAB as a calculator we simply type a mathematical expression into the command window after the
command line prompt >>, and press enter. MATLAB prints the result back to the command window.
Computer programs written in MATLAB are text files containing hundreds of lines of mathematical
expressions.

Editor

Command
Window

Command
Working
line
directory

Figure 1-MATLAB programming environment

2. Basic arithmetic operators in MATLAB

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

4. Variables and Assignment Statement

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

 The command window output can be suppressed by using semicolon


Examples:
>> a=3;b=a+2;a=10*a+b
a =
35

>> b=2;h=5;I=b*h^3/12
I =
20.8333

4.1. Variable Names

Legal names consist of any combination of letters, digits and ‘_’ , starting with a letter.
MaxStress, friction_loss, Y, y, d6f2hA, a_2

 Illegal names: 3a, &d


>> 3a=4
??? 3a=4
|
Error: Unexpected MATLAB expression.

Northumbria University, Mechanical Engineering Division © 2010 Alireza Maheri 3


Computer Programming with MATLAB

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

 MATLAB is case sensitive: a and A are treated as two different variables


>> a=3; A+2
??? Undefined function or variable 'A'.

 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

 We can change special names during programming


>> i=5
i =
5
>> 5+i
ans =
10

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 =

Northumbria University, Mechanical Engineering Division © 2010 Alireza Maheri 4


Computer Programming with MATLAB
0.0333
1
 
(  
5 1
)
6 30
Example 2:
>> 3*20/2*2+((4+2*3)^2)/4
ans =
85
Example 3:
Maximum normal stress in a rectangular cantilever beam supporting a tip load F:
Mc h bh 3 6 Fl
  ; M  Fl ; c  ; I    2
I 2 12 bh
MaxNormStress=(6*F*l)/(b*h^2)
Or:
MaxNormStress=6*F*l/(b*h^2)
Or:
MaxNormStress=6*F*l/b/h^2

6. Scalars

In MATLAB all variables are treated as matrix.


A scalar is a 1x1 matrix or an element of another matrix.

6.1. Scalar Functions

sin trigonometric sine


cos trigonometric cosine
tan trigonometric tangent
asin trigonometric inverse sine (arcsine)
acos trigonometric inverse cosine (arccosine)
atan trigonometric inverse tangent (arctangent)
exp exponential
log natural logarithm
abs absolute value
sqrt square root
rem remainder

>> rem(27,6)
ans =
3

round round towards nearest integer

>> round(1.2)
ans =
1

>> round(-4.6)
ans =
-5

>> round (1.5)


ans =
2

>> round (-1.5)


Northumbria University, Mechanical Engineering Division © 2010 Alireza Maheri 5
Computer Programming with MATLAB
ans =
-2
floor round towards negative infinity

>> floor(2.3)
ans =
2

>> floor(-2.3)
ans =
-3

ceil round towards positive infinity

>> ceil (2.3)


ans =
3

>> ceil(-2.3)
ans =
-2
fix round towards zero

>> fix (2.3)


ans =
2

>> fix(-2.3)
ans =
-2

7. Vectors

A vector is a 1xn or nx1 matrix OR one row or one column of another matrix.

7.1. Constructing a vector in MATLAB

Constructing a row vector


>> 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

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

Constructing a column vector


>> 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

Northumbria University, Mechanical Engineering Division © 2010 Alireza Maheri 6


Computer Programming with MATLAB
Constructing a column vector from a row vector using transpose ‘
>> 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

Constructing a row vector from a column vector using transpose ‘


>> 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

Retrieving an element of a vector


>> a=[5 8 1.2 -7.4 12 45 -3.5]; a(5)
ans =
12.0000
Retrieving part of a vector
>> a=[5 8 1.2 -7.4 12 45 -3.5]; a(3:5)
ans =
1.2000 -7.4000 12.0000

Removing part of a vector


>> a=[5 8 1.2 -7.4 12 45 -3.5]; a(3:5)=[]
a =
5.0000 8.0000 45.0000 -3.5000

Constructing a vector by two or more vectors


>> b=[5 8 1.2 -7.4]; c=[450 200 700];a=[b,c]
a =
5.0000 8.0000 1.2000 -7.4000 450.0000 200.0000 700.0000

Constructing a vector by parts of two or more vectors


>> b=[5 8 1.2 -7.4]; c=[450 200 700];a=[b(1:2),c(3)]
a =
5 8 700

Constructing a vector by sequence of numbers


>> a=[2:1:7]
a =
2 3 4 5 6 7

Constructing a vector by series of random numbers using rand function


>> a=rand(1,6)
a =
0.9501 0.2311 0.6068 0.4860 0.8913 0.7621
In case of a column vector:
>> a=rand(6,1)
a =
0.4565
0.0185
0.8214
0.4447
0.6154
0.7919

Constructing a vector of zeros using zeros function


>> a=zeros(1,4)
Northumbria University, Mechanical Engineering Division © 2010 Alireza Maheri 7
Computer Programming with MATLAB
a =
0 0 0 0
In case of a column vector:
>> a=zeros(4,1)
a =
0
0
0
0

Constructing a vector of ones using ones function


>> a=ones(1,4)
a =
1 1 1 1

In case of a column vector:


>> a=ones(4,1)
a =
1
1
1
1

7.2. Vector functions


All scalar functions can be used on vectors with the operation taking place element-wise.
Example:
>> a=[5 8 1.2 -7.4]; sin(a)
ans =
-0.9589 0.9894 0.9320 -0.8987

max largest component


>> a=[5 8 1.2 -7.4];max(a)
ans =
8

min smallest component


>> a=[5 8 1.2 -7.4]; min(a)
ans =
-7.4000

length length (the number of elements) of a vector


>> a=[5 8 1.2 -7.4]; length(a)
ans =
4

sort sort in ascending or descending order


>> a=[5 8 1.2 -7.4]; sort(a)
ans =
-7.4000 1.2000 5.0000 8.0000

>> a=[5 8 1.2 -7.4]; sort(a,'descend')


ans =
8.0000 5.0000 1.2000 -7.4000

sum sum of elements


>> a=[5 8 1.2 -7.4];sum(a)
ans =
6.8000

prod product of elements


>> a=[5 8 1.2 -7.4];prod(a)

Northumbria University, Mechanical Engineering Division © 2010 Alireza Maheri 8


Computer Programming with MATLAB
ans =
-355.2000

median median value


>> a=[5 8 1.2 -7.4];median(a)
ans =
3.1000

mean mean value


>> a=[5 8 1.2 -7.4];mean(a)
ans =
1.7000

std standard deviation


>> a=[5 8 1.2 -7.4];std(a)
ans =
6.6743

find find elements


>> a=[5 8 0 -7.4];find(a) (this statement finds the index of the non-zero elements)
ans =
1 2 4

>> 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

7.3. Element-wise operators


 element-wise summation +
>> a=[5 8 0 -7.4];b=[3 2 67 -1];a+b
ans =
8.0000 10.0000 67.0000 -8.4000

 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 row by row


>> a=[2,3,5 ; 7,6,12 ; 1,-3,4]
a =
2 3 5
7 6 12
1 -3 4
Or alternatively:
>> a=[2 3 5; 7 6 12; 1 -3 4]
a =
2 3 5
7 6 12
1 -3 4

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

Retrieving part or an element of a matrix


m =
2 3 5 14 -4
7 6 9 -3 12
0 25 1 -3 4
10 -76 -12 30 98

>> m(2,3)
ans =
9

>> m(2:4,1:3)
ans =
7 6 9
0 25 1
10 -76 -12

Removing columns from a matrix


m =
2 3 5 14 -4
7 6 9 -3 12
0 25 1 -3 4

>> m(:,3)=[]
m =
2 3 14 -4
7 6 -3 12
0 25 -3 4

Removing rows from a matrix


m =
2 3 5 14 -4
7 6 9 -3 12
0 25 1 -3 4

>> m(2,:)=[]
m =
2 3 5 14 -4
0 25 1 -3 4

Removing multiple rows or columns from a matrix


Northumbria University, Mechanical Engineering Division © 2010 Alireza Maheri 11
Computer Programming with MATLAB
m =
2 3 5 14 -4
7 6 9 -3 12
0 25 1 -3 4

>> m(2:3,:)=[]
m =
2 3 5 14 -4

Constructing a matrix by series of random numbers using rand function


>> a=rand(3,6)
a =
0.9218 0.4057 0.4103 0.3529 0.1389 0.6038
0.7382 0.9355 0.8936 0.8132 0.2028 0.2722
0.1763 0.9169 0.0579 0.0099 0.1987 0.1988

Constructing a matrix of zeros using zeros function


>> a=zeros(3,3)
a =
0 0 0
0 0 0
0 0 0

Constructing a matrix of ones using ones function


>> a=ones(4,2)
a =
1 1
1 1
1 1
1 1

Constructing a unit matrix of ones using eye function


>> a=eye(3)
a =
1 0 0
0 1 0
0 0 1

8.2. Matrix operators


The following matrix operations are available in MATLAB:
+ addition
- subtraction
* matrix multiplication
^ power
‘ transpose
\ left division
/ right division

See MATLAB help for examples

8.3. Matrix functions


All scalar functions can be used on matrices with the operation taking place element-wise.
Example:
a =
1 3 5
12 6 -5
2 -3 14

>> 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

In order to find the minimum (or maximum) element of a matrix:


a =
1 3 5
12 6 -5
2 -3 14
>> min(a)
ans =
1 -3 -5
>> min(min(a))
ans =
-5
Other functions
eye identity matrix
zeros matrix of zeros
ones matrix of ones
diag extract diagonal of a matrix or create diagonal matrices
triu upper triangular part of a matrix
tril lower triangular part of a matrix
rand randomly generated matrix
size size of a matrix
det determinant of a square matrix
inv inverse of a matrix
rank rank of a matrix
rref reduced row echelon form
eig eigenvalues and eigenvectors
poly characteristic polynomial
norm norm of matrix (1-norm, 2-norm, ∞ -norm)
cond condition number in the 2-norm
lu LU factorization
qr QR factorization
chol Cholesky decomposition
svd singular value decomposition

For examples see MATLAB help

Northumbria University, Mechanical Engineering Division © 2010 Alireza Maheri 13


Computer Programming with MATLAB
9. M-files
M-files are text files with the extension of “.m”. These files contain a series of commands that can be
called from command window or from other m-files. There are two types of m-files: Scripts and
Functions. These files are used to write programs in MATLAB.

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: FileNewM-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)
% ================================================

clc % Clear command window


clear all %Clear all variables previously generated and stored in MATLAB

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.

10. Conditional statements


There are occasions that we want that the program takes different routs of operations based on decisions
made. In these cases we can use if statement.

10.1. if-end statement


syntax:
if expression
commands (executed only if expression is true)
end

Northumbria University, Mechanical Engineering Division © 2010 Alireza Maheri 14


Computer Programming with MATLAB
if-end statement is the simplest form of if-statement, in which the program executes some of the
commands only when some conditions are met. Assume that in your code, you also want to compare the
maximum stress with a given allowable stress. The code returns the maximum stress only if it is less than
the allowable stress. StressInBeams_1 has been modified to StressInBeams_2 with this property.

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)
% ================================================

clc % Clear command window


clear all %Clear all variables previously generated and stored in MATLAB

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.

10.2. if-else-end statement


syntax:
if expression
commands 1 (executed if expression is true)
else
commands 2 (executed if expression is false)
end

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)
% ================================================

Northumbria University, Mechanical Engineering Division © 2010 Alireza Maheri 15


Computer Programming with MATLAB
clc % Clear command window
clear all %Clear all variables previously generated and stored in MATLAB

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')

10.3. Nested if statement


syntax:
if expression1
commands 1 (executed if expression1 is true)
elseif expression2
commands 2 (executed if expression1 is false but expression2 is true)
else
commands 3 (executed if both expression1 and expression2 are false)
end

10.4. Logical Operators


There are three logical operators available in MATLAB. These operators are used to make multi-
conditional expressions.

Logical Operators Operation Example


| Or a<2 | b==5
& And a>=0 & x+y^2<0
~ Not ~x
Table 4-Logical operators
Example:
if ~((a<2 & b==3) | (a*b<0))
x=x+3
end

11. for statement


syntax:
for a1 : inc : a2
commands (executed for all values from a1 to a2 by increment of inc)
end

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.

Northumbria University, Mechanical Engineering Division © 2010 Alireza Maheri 16


Computer Programming with MATLAB
StressInBeams_4.m
% ================================================
% This script calculates the maximum normal stress in a rectangular cantilever beam
% for various lengths 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)
% ================================================

clc % Clear command window


clear all %Clear all variables previously generated and stored in MATLAB

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
>>

11.1. Nested for-loops


Assume that you want to study the effect of both force and length on the maximum stress. The code
below changes both length (3 to 5 m with 1 m increments) and force (from 1 to 10 KN with 1 KN
increments) and display the results with a proper format.

Northumbria University, Mechanical Engineering Division © 2010 Alireza Maheri 17


Computer Programming with MATLAB
StressInBeams_5.m
% ================================================
% This script calculates the maximum normal stress in a rectangular cantilever beam
% for various lengths and forces 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)
% ================================================

clc % Clear command window


clear all %Clear all variables previously generated and stored in MATLAB
format short g % Set display format for output

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.

Table 5 shows a list of display formats.

Table 5-Display formats


12. while statement
syntax:
while expression
commands (execute repeatedly while expression is true)
end

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)

Northumbria University, Mechanical Engineering Division © 2010 Alireza Maheri 19


Computer Programming with MATLAB
% all_stress: allowable normal stress (MPa)
% ================================================

clc % Clear command window


clear all %Clear all variables previously generated and stored in MATLAB

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
>>

Northumbria University, Mechanical Engineering Division © 2010 Alireza Maheri 20


Computer Programming with MATLAB
PART II-Writing GUIs
13. What is a GUI
A Graphical User Interface (GUI) is used to ease the communication between the user and the main code.
GUIs include one main figure as a container and some components such as edit boxes, texts, radio
buttons, list boxes, plots, check boxes, etc. Figure 2 shows a GUI developed in MATLAB.

Push button
Check box Axes

List box Text

Radio
button

Edit box

Figure 2- A GUI written in MATLAB

Northumbria University, Mechanical Engineering Division © 2010 Alireza Maheri 21


Computer Programming with MATLAB
Each single component of a GUI is defined with a series of properties. Some of these properties that we
need here to start are shown in Table 6.

Style Type of uicontrol


pushbutton, togglebutton, radiobutton, checkbox, edit, text,
slider, listbox, popupmenu
Position Size and location of [x1 y1 w h] (x1, y1, w and h are the coordinates of the lower
uicontrol left corner and the width and height of a rectangle in which the
uicontrol fits in)
String Uicontrol label A string of characters
BackgroundColor Background colour Colour in code (blue, red, …) or in RGB format
ForegroundColor Colour of the string Colour in code (blue, red, …) or in RGB format
Parent Uicontrol object's A figure, uipanel, or uibuttongroup
parent
Tag User-specified A string of characters
object identifier
Table 6-Some properties of objects in a GUI

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.

14. Writing a GUI


Assume that you want to run the previous code for different forces. One way is to change the value of the
force in the force assignment statement (f=3000;), save the file and run the script from command line.
Another, and easier, way is to write a GUI with one edit box for entering the value of the force, one
pushbutton for executing the code and another edit box for displaying the result. The following script
generates such a GUI. Make a new file, type the following lines and save it with a proper name (here
MyFirstGUI).

MyFirstGUI.m
%This script generates a GUI with two edit boxes and one pushbutton

%Main figure containing the uicontrols


my_figure=figure('Position', [50,50,400,200]);

%Edit box for the user input


uicontrol('Parent',my_figure,'tag','force','Style','edit','Position',[20,100,50,20])

%Edit box displays the result


uicontrol('Parent',my_figure,'tag','result','Style','edit',...
'Position',[100,100,50,20])

%Push button for execution of script StressInBeams_7


uicontrol('Parent',my_figure,'tag','run','Style','pushbutton',...
'Position',[200,100,50,20],'string','RUN','callback','StressInBeams_7')

 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)
% ================================================

clc % Clear command window


clear all %Clear all variables previously generated and stored in MATLAB

%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));

findobj is similar to find command, but operates on objects such as uicontrols


 num2str command converts a number to string
 str2num command converts a string to number
 get command gets a property of a specified object
 set command sets a property of a specified object

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.

Figure 4-MyFirstGUI input/output

Northumbria University, Mechanical Engineering Division © 2010 Alireza Maheri 24

You might also like