Lecture Note #7
Lecture Note #7
M-files is a text file that contains one or more MATLAB commands and
comments (optional).
2
How to Create, Open, Save, and Run a Script File
3
How to Create, Open, Save, and Run a Script File
After writing the script follow the below steps to save the M-file:
1. Click on save button.
2. Put a suitable file name.
3. Click save.
The * mean
that you need
to save the
file
4
How to Create, Open, Save, and Run a Script File
To run the script click on run:
5
Basics of Writing Script File
As previously done in the command window, it is possible to conduct
mathematical operations on any numbers or defined variables which contain
numbers in MATLAB Script file. The operations include: addition, subtraction,
multiplication, division, and raising to a power.
The order of operations in MATLAB script files and function files remains the
same as discussed earlier for the command window (Lecture Note #2-slide
#12).
6
Basic Script File – Example
Example 1: Create a MATLAB script file which calculates and only displays the
sum of odd numbers which exist between 1 and 100.
Script:
clear
a=1:2:100;
b=sum(a);
disp(b);
7
Basic Script File – Example
Example 2: Create a MATLAB script file which calculates the value of x from the
following series. Display x value as an output.
(1.7∗12)2 (1.9∗12)2 (2.1∗12)2 (2.3∗12)2 (2.5∗12)2
𝑥𝑥 = + + + +
1 10 100 1000 10000
Script:
clear
a=1.7:0.2:2.5;
b=0:4;
x=sum((a*12).^2./10.^b);
disp(x);
8
Basic Script File – Example
Example 3: A solid waste treatment facility needs to be built, the capacity
volume of the tank is 13500m3 the construction cost is 200BD per square meter
for the base, and 157BD Per square meter for the wall surface.
Write a MATLAB script to determine the height ℎ and the radius 𝑟𝑟 that will give
the minimum construction cost, use 𝑟𝑟 value ranging from 10m to 20m at an
increment of 0.5m. Finally display the value of the minimum cost, and the
corresponding ℎ and 𝑟𝑟 values in the command window.
9
Basic Script File – Example
Example 3 solution:
The question requires to find the optimum h and r values which would
produce the lowest cost.
In order to find that, we must first calculate the cost of each of the 21
possible options (for r = 10 to 20 @ increment of 0.5m).
Since the required volume is fixed, we can re-arrange its equation to find
the value of h which corresponds to each r value.
V =𝜋𝜋𝑟𝑟^2 ℎ >> ℎ = V/(𝜋𝜋𝑟𝑟^2)
After finding h values, the wall surface area (W) and base area (A) can be
calculated for each of the 21 options.
After calculating W and A, the cost can be estimated for each of the 21
options using the following equation:
Cost = C = 200A + 157W
All that remains after that is to find the minimum cost and the value of h
and r which will produce it.
10
Basic Script File – Example
Script:
Output in Command window:
V=13500;
Minimum cost is:
r=10:0.5:20;
4.2397e+05
h=V./(pi*r.^2);
W=2*pi*r.*h;
A=pi*r.^2; Corresponding r value:
C=200*A+157*W; 15
Cmin=min(C);
hmin=h(find(C==min(C))); Corresponding h value:
rmin=r(find(C==min(C)));
19.0986
disp('Minimum cost is:');
disp(Cmin);
disp('Corresponding r value:');
disp(rmin);
disp('Corresponding h value:');
disp(hmin);
11
Basic Script File – Example
Example 4: Create a MATLAB script file which calculates the value of y from the
following expression. Display y value as an output. (Note that x = 2 and t = 𝜋𝜋⁄4)
2𝑒𝑒 2𝑡𝑡 ∗ cos 𝑡𝑡 − 𝑥𝑥 2
𝑦𝑦 =
2𝑥𝑥 − sin(𝑡𝑡)
Script:
clear
x=2;
t=pi/4;
y=(2*exp(2*t)*cos(t) - x^2)/(2*x - sin(t));
disp(y);
12
For Loops
As a user, it is not desired to write a command multiple times to execute the
same task multiple times. This is why it is necessary to introduce a command
that would repeat the same task a known number of times to generate the
required output. These commands are known as loops.
One of the basic loops which are commonly used is the for loops.
For loops define a variable’s starting and ending values. The variable’s value
gets updated after completing each iteration of the loop.
For a basic for loop as shown below, the step size is one which means that
the value of the defined variable increases by 1 after completing each
iteration of the loop.
The number of times the code is executed = upper bound − lower bound + 1
Sample for basic for loop:
for i = starting value : ending value
%command to be executed n number of time
end
13
For Loops - Example
Examples for basic for loops:
Script: Script:
clear clear
for i = [1:5] a=[5 8 3 4 12];
disp(i); for i = a
end disp(i);
end
14
For Loops - Example
Examples for for loops with defined step size:
Script: Script:
clear clear
for i = 5:-2:-2 a=[5 8 3 4 12];
disp(i); for i = length(a):-1:1
end disp(a(i));
end
15
For Loops - Example
Example: using a for loop, find the summation of the even numbers between 2
and 50. Output the result in the command window.
Option 1 Option 2 Option 3
Script: Script: Script:
clear clear clear
sum=0; sum=0; sum=0;
for i = 2:2:50 a = [2:2:50] a = [2:2:50]
sum = sum + i; for i = a for i = 1 : length(a)
end sum = sum + i; sum = sum + a(i);
disp(sum); end end
disp(sum); disp(sum);
Output:
650
16
Defining 2D Array Variables
As shown in the previous examples, initializing the variables is usually done
as the first step of writing a script.
For 2D Array variables, it is possible to define them as shown below:
Define a 4x4 matrix named a with all elements being equal to zero:
Option 1 Option 2 0 0 0 0
clear clear a= 0 0 0 0
a(4,4)=0; a=zeros(4); 0 0 0 0
0 0 0 0
Define a 4x4 matrix named a with all elements being equal to zero but
elements 2,3 & 4,4:
Option 1 Option 2 0 0 0 0
Clear clear
a(2,3)=1; a=zeros(4); a= 0 0 1 0
0 0 0 0
a(4,4)=2; a(2,3)=1 0 0 0 2
a(4,4)=2
17
For Loops - Example
Example: using a for loop, generate the identity matrix of size 6x6. Output the matrix
in the command window.
Script:
clear
for i = 1:6
a(i,i) = 1;
end
disp(a);
Note: this will give this warning message below:
To prevent this error from appearing , it is necessary to define Output in Command window:
the size of a before the for loop. As done below: 1 0 0 0 0 0
Script: 0 1 0 0 0 0
clear
a = zeros(6); 0 0 1 0 0 0
for i = 1:6 0 0 0 1 0 0
a(i,i) = 1;
end 0 0 0 0 1 0
disp(a); 0 0 0 0 0 1
18
For Loops - Example
Example: using a for loop, find the summation of all numbers in the vector a. Output
the result in the command window.
a = [ 50, 93, 10, 67, 38, 71, 96 ]
Option 1 Option 2
Script: Script:
clear; clear;
a = [ 50, 93, 10, 67, 38, 71, 96 ]; a = [ 50, 93, 10, 67, 38, 71, 96 ];
sum = 0; sum = 0;
for i = 1 : length(a) for i = a
sum = sum + a(i); sum = sum + i;
end end
disp(sum); disp(sum);
19
For Loops - Example
Example: using a for loop, find the average of all numbers in the vector a. Output the
result in the command window.
a = [ 50, 93, 10, 67, 38, 71, 96 ]
Option 1 Option 2
Script: Script:
clear; clear;
sum = 0; sum = 0;
a = [ 50; 93; 10; 67; 38; 71; 96 ]; a = [ 50 93 10 67 38 71 96 ];
len = length(a); for i = a
for i = 1 : len sum = sum + i;
sum = sum + a(i); end
end disp(sum/length(a));
disp(sum/len);
20
For Loops - Example
Example: using a for loop, find the value of w using the following series, assume that x
= 1.2. Output the result in the command window.
3 6 12 24 1536
𝑤𝑤 = 20 + + 2 + 2 + 2 …+
2∗𝑥𝑥 2 4∗𝑥𝑥 6∗𝑥𝑥 8∗𝑥𝑥 20∗𝑥𝑥 2
Option 1 Option 2
Script: Script:
clear; clear;
w = 20; x = 1.2;
x = 1.2; w = 20;
for i = 1 : 10 j = 3;
w=w+(3*2^(i-1)/(2*i*x^2)); for a=2:2:20
end w=w+j/(a*x^2);
disp(w); j=j*2;
end
disp(w);
Output in Command window:
143.5979
21
If Statements
It is essential for most of the scripts and functions to have a decision
statement which will allow MATLAB to decide which command should be
executed and subsequently the outcome that would be generated.
If statements do the above by specifying a criteria which will allow MATLAB to
decide which path should be taken.
If statements must always be followed by the condition to be set.
At the end of an if statement, End must be written to indicate where the if
statement ends.
It is common to have subsequent result which will be executed when the
condition of the if statements is not satisfied. This can be done simply by
typing Else. Everything following else until End if will be executed if the
condition is not satisfied.
In some of the cases, multiple if statements are required to write a script or
function that can test more than one condition inside of each other. This can
be done by typing Elseif as a single word followed by the condition.
22
If Statements
Samples for basic if statements:
if Condition
%Commands to be executed if condition is satisfied
end
if Condition
%Commands to be executed if condition is satisfied
else
%Commands to be executed if the condition is not satisfied
end
if Condition1
%Commands to be executed if condition1 is satisfied
elseif Condition2
%Commands to be executed if condition2 is satisfied
else
%Commands to be executed if both conditions are not satisfied
end
23
Logical Conditions
As discussed in Lecture Note #3, all logical conditions must contain any of the
operators mentioned in the following table:
Operator Condition
a==b The value of a equals the value of b
a>b The value of a is larger than the value of b
a>=b The value of a is larger than or equal to the value of b
a<b The value of a is smaller than the value of b
a<=b The value of a is smaller than or equal to the value of b
a~=b The value of a does not equal the value of b
A slight difference for having multiple logical conditions in MATLAB scripts and
functions is that it is required to write double |/& for Or/And operators.
Expression Operator a b a && b a || b
And (Condition 1) && (Condition 2) … && (Condition n) T T T T
or (Condition 1) || (Condition 2) … || (Condition n) T F F T
Not ~(Condition(s)) F T F T
F F F F
24
Logical Conditions - Examples
Writing the below logical conditions in MATLAB command window yields the
following: >> A = [ 2 7 6 ; 9 0 5 ; 3 0.5 6 ];
>> B = [ 8 7 0 ; 3 2 5 ; 4 -1 7 ];
>> 5 > 8
ans = >> A == B
0 ans =
0 1 0
>> 4 <= 9 0 0 1
ans = 0 0 0
1
Scalars Matrices >> C = A < B
>> a = 6 ~= 4 C =
a = 1 0 0
1 0 1 0
1 0 1
>> b = a ~= 1
>> A>5
b = ans =
0 0 1 1
1 0 0
0 0 1
25
Logical Conditions - Examples
>> (5<6)&&(3<7)
ans = >> A = [ 2 7 6 ; 9 0 5 ; 3 0.5 6 ];
1
>> B = [ 8 7 0 ; 3 2 5 ; 4 -1 7 ];
>> ~((5<6)&&(3>=7))
ans = >> A == B & A > 5
1 ans =
0 1 0
>> 5 && 3 0 0 0
ans = 0 0 0
1
Scalars Matrices >> C = A < B | A > 5
>> (5>=1) || 0
C =
ans = 1 1 1
1 1 1 0
>> -1 || (5==7) 1 0 1
ans = >> ~(A < B | A > 5)
1 ans =
0 0 0
>> -1 && ~0 0 0 1
ans = 0 1 0
1 26
If Statements - Examples
Example: write a script with if statement which outputs “Positive” if a number
(a) is positive.
Script:
clear;
a=4;
if a>0
disp('Positive');
end
If a > 0
‘Positive’ No output
27
If Statements - Examples
Example: write a script with if statements which outputs “Positive”, “Negative”, and
“Zero” if a number (a) is positive, negative, or zero.
Option 1 Option 2
Script: Script:
clear; clear;
a=0; a=0;
if a>0 if a>0
disp('Positive'); disp('Positive’);
elseif a<0 else
disp('Negative'); if a<0
else disp('Negative’);
disp('Zero'); else
end disp('Zero’);
If a > 0 end
end
- or 0
Possible ‘Positive’ If a < 0
outcomes chart
‘Negative’ ‘Zero’
28
If Statements - Examples
Example: the vector below contains students marks, write a MATLAB script which finds the
number of passed students (passing grade is 60%), and the number of student who got a
full mark. Output both answers in the command window.
a = [ 50, 93, 100, 67, 38, 71, 96, 80, 36, 90, 100]
Option 1: using sum function
Script:
clear;
a = [50, 93, 100, 67, 38, 71, 96, 80, 36, 90, 100];
Pass=sum(a>=60);
FullMark=sum(a==100);
disp('Passed student');
disp(Pass);
disp('Student with Fullmark ');
disp(FullMark);
Output in Command window:
Passed student
8
Student with Fullmark
2 29
If Statements - Examples
Option 2: using if statement
Script:
clear;
a = [50, 93, 100, 67, 38, 71, 96, 80, 36, 90, 100];
Pass = 0;
FullMark = 0;
for i = 1 : length(a)
if a(i)>=60
Pass = Pass+1;
if a(i)==100
FullMark = FullMark+1;
end
end
end
disp('Passed student');
disp(Pass);
disp('Student with Fullmark ');
disp(FullMark);
30
If Statements - Examples
Example: Write a MATLAB script which finds the percentage of positive numbers in a
vector (a). Note that a might be a row vector or a column vector with any size.
a = [50; -93; -100; -67; 38; -71; 96; 80; 36; -90; 0]
32
Nested For Loops
As a user, can also place multiple for loops inside a for loop or each other. This is
typically called nested for loops.
It is important to predict the number of times each for loop will iterate when
running the code. While the outer for loop (the for loop which is mentioned in
the beginning) will run a number of times equal to the value discussed earlier in
this lecture note, the times that the inner for loops will run will be a
multiplication of the outer for loop iterations times the inner for loop iterations.
An example of a nested for loop is shown below:
for i = 1:4
4 times
%commands to be executed 4 times
4 times
for j = 1:5
5 times
a = [1 5 7 3; 2 5 2 8; 3 6 8 4; 4 7 9 1]
Script:
clear; 1 5 7 3
clc; 2 5 2 8
a=[1 5 7 3; 2 5 2 8; 3 6 8 4; 4 7 9 1]; 1,1 1,2 1,3 1,4
3 6 8 4
atrans=a; 4 7 9 1 2,1 2,2 2,3 2,4
for i = 1 : size(a,1)
3,1 3,2 3,3 3,4
for j = 1 : size(a,2) 1 2 3 4
if i~=j 4,1 4,2 4,3 4,4
5 5 6 7
atrans(i,j)=a(j,i); 7 2 8 9
end 3 8 4 1
end
end
a=atrans;
disp(a);
34
Nested For Loops - Examples
Example: Using for loops, write a script which copies the upper triangle to the lower
triangle inside a square array.
a = [1 5 7 3; 2 5 2 8; 3 6 8 4; 4 7 9 1]
Script:
clear;
clc; 1 5 7 3
a=[1 5 7 3; 2 5 2 8; 3 6 8 4; 4 7 9 1]; 2 5 2 8
1,1 1,2 1,3 1,4
if size(a,1)==size(a,2) 3 6 8 4
for i = 1 : size(a,1) 4 7 9 1 2,1 2,2 2,3 2,4
for j = 1 : size(a,2) 3,1 3,2 3,3 3,4
if i>j 1 5 7 3
4,1 4,2 4,3 4,4
a(i,j)=a(j,i); 5 5 2 8
end 7 2 8 4
end 3 8 4 1
end
disp(a);
else
disp('array is not square')
end
35
Nested For Loops - Examples
Example: write a script which finds the percentage of zero values in a variable. Note
that the variable can be a scalar, vector, or matrix. Assume that the entered variable is
shown below:
a = [1 2 3 4; 0 5 6 7; 0 0 8 9; 0 0 0 1]
Option 1: using sum function
Script:
clear;
a=[1 2 3 4; 0 5 6 7; 0 0 8 9; 0 0 0 1];
percentage = 100* sum(sum(a==0))/numel(a);
disp(percentage)
Script: Script:
clear; clear;
a=[1 2 3 4; 0 5 6 7; 0 0 8 9; 0 0 0 1]; a=[1 2 3 4; 0 5 6 7; 0 0 8 9; 0 0 0 1];
zerocount = 0; len = numel(a);
for i = 1:size(a,1) zerocount = 0;
for j = 1:size(a,2) for i = 1 :len
if a(i,j)==0 if a(i)==0
zerocount = zerocount+1; zerocount = zerocount+1;
end end
end end
end disp(100*zerocount/len);
disp(100*zerocount/numel(a));
37
Nested For Loops - Examples
Example: Write a script which finds the value of 𝑒𝑒 𝑥𝑥 using the following series. Use n=15,
x=2.5.
𝑥𝑥 2 𝑥𝑥 3 𝑥𝑥 4 𝑥𝑥 𝑛𝑛
𝑒𝑒 𝑥𝑥 = 1 + 𝑥𝑥 + + + + ⋯+
2! 3! 4! 𝑛𝑛!
Option 1: using for loop and Option 2: using for loop and
factorial function product function
Script: Script:
clear; clear;
x = 2.5; x = 2.5;
sum = 0; sum = 0;
for i = 0 : 15 for i = 0 : 15
sum=sum+x^i/factorial(i); sum=sum+x^i/prod(1:i)
end end
disp(sum); disp(sum);
38
Nested For Loops - Examples
Script:
clear;
x = 2.5;
sum = 0;
for i = 0 : 15
fact = 1;
for j = 1 : i
fact = fact * j;
end
sum = sum + x^i/fact;
end
disp(sum);
39
For Loops and If Statement - Examples
Example: Write a script which finds the maximum deflection for the below beam. Also,
find where it is located. The deflection (y) is calculated using the following expression:
𝑤𝑤𝑜𝑜
𝑦𝑦 = (−𝑥𝑥 5 + 2𝐿𝐿2 𝑥𝑥 3 − 𝐿𝐿4 𝑥𝑥)
Option 1: using max function 120𝐸𝐸𝐸𝐸𝐸𝐸
Where:
Script:
clear; E = 50000kN/mm 2, L= 600cm,
e = 5e4; I = 6x106 mm, Wo= 10kN.
L = 6000;
i = 6e6;
w = 10;
MaxDef = 0; y
max
x = 0:L;
y = w / (120*e*i*L) * ((-x).^5 + 2 * L^2 * x.^3 - L^4 * x);
index = find(max(abs(y))==abs(y));
disp('The maximum deflection =');
disp(y(index));
disp('The distance of the maximum deflection =');
disp(x(index));
40
For Loops and If Statement - Examples
Option 2: using for loop and if statement
Output in Command window:
Script: The maximum deflection =
clear;
-103.0380
e = 5e4;
L = 6000;
i = 6e6; The distance of the maximum deflection =
w = 10;
2683
MaxDef = 0;
for x = 0:L
y = w / (120*e*i*L) * ((-x)^5 + 2 * L^2 * x^3 - L^4 * x);
if abs(MaxDef) < abs(y)
MaxDef = y;
MaxDefDist = x;
end
end
disp('The maximum deflection =');
disp(MaxDef);
disp('The distance of the maximum deflection =');
disp(MaxDefDist);
41
While Loops
Another type of loops which is commonly used for coding is the while loops.
While loops define a condition which must be violated to break from the
while loop. While that condition is satisfied, the while loop will continue to
iterate.
It is important to note that there has to be a command which allows the
condition to change, otherwise; it would get stuck. As an example, if a
condition of x < 5 is set, the value of x should be able to update while the
loop is iterating; otherwise it will not break from the while loop.
The number of times the code is executed is equal to the number of times
the condition is satisfied.
Sample for basic for loop:
while condition
%command to be executed while the condition is satisfied.
end
42
While Loops
Example: Write a script having a while loop which displays the numbers 1 through 5.
Script:
clear;
i=1;
while i<=5
disp(i);
i=i+1;
end
43
While Loops
Example: Write a script having a while loop which finds and only displays the summation
of the numbers 1 to 5.
Script:
clear;
sum = 0;
i=1;
while i<=5
sum=sum+i;
i=i+1;
end
disp(sum)
44
While Loops
Example: Write a script which finds the position of the first zero in a vector named a.
(assume that the vector a contain at least one zero)
a = [54,23,-65,0.5,12,55,0,76,12,0];
Script: Script:
clear; clear;
a=[54 23 -65 0.5 12 55 0 76 12 0]; a=[54 23 -65 0.5 12 55 0 76 12 0];
index=find(a==0); pos = -1;
pos=(index(1)); for i = 1:length(a)
disp(pos); if a(i)==0 && pos==-1
pos=i;
end
end
disp(pos);
45
While Loops
Option 3: using while loop
Script:
clear;
a=[54 23 -65 0.5 12 55 0 76 12 0];
i=1;
while a(i)~=0
i=i+1;
end
disp(i);
46
While Loops
Example: The formula below will converge to a root, write a MATLAB script which finds:
1. The root of the equation using x0=0, stop the loop when the difference between
𝑥𝑥𝑖𝑖 and 𝑥𝑥𝑖𝑖−1 become less than 0.0001.
𝑒𝑒 −𝑥𝑥𝑖𝑖 − 𝑥𝑥𝑖𝑖
2. How many iteration will take to reach the solution. 𝑥𝑥𝑖𝑖+1 = 𝑥𝑥𝑖𝑖 −
−𝑒𝑒 −𝑥𝑥𝑖𝑖 − 1
Script:
clear;
x = 0; Output in Command window:
oldx = -99991; The root of the equation is:
iterations = 0;
while abs(x-oldx) > 0.0001 0.5671
oldx=x;
x = x-(exp(-x)-x)/(-exp(-x)-1);
The number of iterations to reach it is:
iterations = iterations + 1;
end 4
disp('The root of the equation is:');
disp(x);
disp('The number of iterations to reach it is:');
disp(iterations);
47
While Loops
Example: A tank formed by attaching a cylinder that have a dimeter 1.2m onto a cone
of height of 60cm, what is the height of the water in meters if the tank is to be filled up
to 3𝑚𝑚3 .
Script: Volume of Cone = 1/3 π r2h, Volume of Cylinder = π r2h
h = 0;
r = 1.2/2; 1.2 m
Coneh = 0.6;
TotalV = 0;
while TotalV<3
h = h+0.001;
if h <= Coneh 0.6 m
TotalV = 1/3*pi*r^2*h;
else
TotalV =1/3*pi*r^2*Coneh + pi*r^2*(h-Coneh);
end Output in Command window:
end The height of the water is:
disp('The height of the water is:')
disp(h); 3.0530
48
Plotting Graphs in MATLAB Script
It is possible to plot a graph as an output from running a script.
The plot can be customized as mentioned in Lecture Note #5.
Example: Write a script which plots y vs. x for x values ranging between -5 to 5
at an increment of 0.1. Note that 𝑦𝑦 = 0.5𝑥𝑥 3 . Make the line color of the plot
green, insert proper axis labels & graph title and turn on the gridlines.
Script:
clear;
x=-5:0.1:5;
y=0.5*x.^3;
plot(x,y,'g')
xlabel('x values')
ylabel('y values')
title('0.5*x^3 chart')
grid on
49
Plotting Graphs in MATLAB Script - Example
Example: Write a script which plots the deflection of the below beam along its length.
Use proper axis labeling and turn on the gridline. The deflection (y) is calculated using
the following expression: 𝑤𝑤𝑜𝑜
𝑦𝑦 = (−𝑥𝑥 5 + 2𝐿𝐿2 𝑥𝑥 3 − 𝐿𝐿4 𝑥𝑥)
120𝐸𝐸𝐸𝐸𝐸𝐸
Where:
Option 1: without using for loop
E = 50000kN/mm2, L= 600cm,
Script: I = 6x106 mm, Wo= 10kN.
clear;
e = 5e4;
L = 6000;
i = 6e6;
y
w = 10;
max
x = 0:L;
y = w / (120*e*i*L) * ((-x).^5 + 2 * L^2 * x.^3 - L^4 * x);
plot(x,y)
xlabel('distance from right edge (mm)')
ylabel('deflection (mm)')
grid on
50
Plotting Graphs in MATLAB Script - Example
Option 2: using for loop
Script:
clear;
e = 5e4;
L = 6000;
i = 6e6;
w = 10;
x=0:L;
for j = 0:L
y(j+1) = w / (120*e*i*L) *
((-j)^5 + 2 * L^2 * j^3 - L^4 * j);
end
plot(x,y)
xlabel('distance from right edge (mm)')
ylabel('deflection (mm)')
grid on
51
Input variables in MATLAB script
So far, all the examples explained have their variables defined within
MATLAB script without the need for the user to input anything.
It is possible in MATLAB to allow the above simply by using a function called
“input”.
Input function must be written as shown below:
a = input(prompt)
Where:
a: is a variable name which will store the input values.
prompt: is a string on the screen which is displayed to the user while the run is
paused and waiting for input from the keyboard. If the user presses the return
key without entering anything, input returns an empty matrix.
52
Input variables in MATLAB script - Example
Example: Write a script which takes the user input number and displays its absolute
value. Assume that the user always inputs numbers, the numbers can be scalar, in a
vector, or a matrix.
Script:
clear;
x = input('Input a variable (scalar, vector, or matrix):');
disp('The absolute value of the variable is:')
disp(abs(x))
Output in Command window:
Input a variable (scalar, vector, or matrix):-5
Scalar
The absolute value of the variable is:
5
53
Input variables in MATLAB script - Example
Example: Write a script which takes the length and width of a rectangle to calculate
and output its perimeter and area. Accept scalar values as an input only.
Script:
Output in Command window:
clear;
L = input('Please input the rectangle length:'); Please input the rectangle length:5
w = input('Please input the rectangle width:'); Please input the rectangle width:2
if length(L)==1 && length(w)==1
disp('The rectangle perimeter is:') The rectangle perimeter is:
disp(2*(L+w)) Scalar
14
disp('The rectangle area is:')
disp(L*w) The rectangle area is:
else 10
disp('The input values are not scalar')
end Output in Command window:
Please input the rectangle
Array length:[5,2]
Please input the rectangle width:2
The input values are not scalar
54
Input variables in MATLAB script - Example
Example: Write a script which takes a shape type and its dimensions to calculate and
output its perimeter and area. Set a value of 1 for rectangle shapes, 2 for square
shapes, and 3 for circle shapes. Accept scalar values as an input only.
Script: disp('The square perimeter is:')
clear; disp(4*L)
S = input('Please input the shape indicator disp('The rectangle area is:')
(1=rectangle, 2=square, 3=circle):'); disp(L^2)
if S==1 else
L = input('Please input the rectangle disp('The input values are not scalar')
length:'); end
w = input('Please input the rectangle elseif S==3
width:'); r = input('Please input the circle radius:');
if length(L)==1 && length(w)==1 if length(r)==1
disp('The rectangle perimeter is:') disp('The circle perimeter is:')
disp(2*(L+w)) disp(2*pi*r)
disp('The rectangle area is:') disp('The circle area is:')
disp(L*w) disp(pi*r^2)
else else
disp('The input values are not scalar') disp('The input values are not scalar')
end end
elseif S==2 else
L = input('Please input the square disp('No shape is defined for this value')
length:'); end
if length(L)==1 55
Input variables in MATLAB script - Example
Example: Write a script which takes the lower and upper bounds of x and plot sin(x) &
cos(x) in one chart against it. Use proper axis labeling and turn on the gridline and
accept only scalar values for the bounds. Note: use 1000 linearly spaced values between
the lower and upper bounds to plot.
Output in Command window:
Script:
clear; Input the lower bound of x:-2*pi
xlow = input('Input the lower bound of x:'); Input the upper bound of x:2*pi
xup = input('Input the upper bound of x:');
if length(xlow)==1 && length(xup)==1
x=linspace(xlow,xup,1000);
subplot(2,1,1)
plot(x,sin(x))
xlabel('angle in radians')
ylabel('sine value')
grid on
subplot(2,1,2)
plot(x,cos(x))
xlabel('angle in radians')
ylabel('cosine value')
grid on
else
disp('The input values are not scalar')
end
56
MATLAB Function Writing
Custom functions can be created in MATLAB by writing a function in the
editor window.
While writing a function, it can be noted that all that have been explained
so far in script writing applies in the same manner while writing a function
(for loops, if statements, while loops, etc…). Notes
Sample for writing a function: • Code above declares a function named Function1 that
accepts inputs C & D and returns outputs A & B.
Output Arguments Input Arguments
• This declaration statement must be the first
function [ A , B ] = Function1( C , D ) executable line of the function.
• The function code saved in a text file with a .m
A = ... extension.
B = ... Function name • The name of the file should match the name of the
function.
end • Valid function names begin with an alphabetic
character, and can contain letters, numbers, or
underscores.
• To be able to execute a function the function file
should be saved in the current folder or in one of
MATLAB search paths
57
How to Create, Open, and Save a Function File
To create a new function file, click on the displayed tools below:
58
How to Create, Open, and Save a Function File
59
How to Call a Function
60
MATLAB Function Writing - Examples
Example1: Write a MATLAB function which generates pi value when called.
Function: Command window:
function [ a ] = pivalue() >> pivalue()
a = pi; ans =
End 3.1416
Example2: Write a MATLAB function which generates two random numbers when called.
Function: Command window:
function [ a , b ] = randvalue() >> randvalue()
a = rand; ans =
b = rand; 0.1270
end >> a=randvalue()
a =
0.6324
>> [a b]=randvalue()
a =
0.2785
b =
0.5469
61
MATLAB Function Writing - Examples
Example3: Write a MATLAB function which calculates the area of a circle when given its
radius as an input.
Function:
function [ a ] = Circlearea( r )
a = pi*r^2;
end
Command window:
>> Circlearea()
Error using Circlearea (line 2)
Not enough input arguments.
>> Circlearea(2.5)
ans =
19.6350
>> Circlearea(2.5:1:5.5)
Error using ^
Inputs must be a scalar and a square matrix.
To compute elementwise POWER, use POWER (.^) instead.
Command window:
>> Circlearea(2.5:1:5.5)
ans =
19.6350 38.4845 63.6173 95.0332
>> Circlearea([2;4])
ans =
12.5664
50.2655
63
MATLAB Function Writing - Examples
Example4: Write a MATLAB function which calculates the area of one or more rectangles
when given its/their lengths and widths.
Function:
function [ a ] = Rectanglearea( h, w )
a = h .* w;
end
Command window:
>> Rectanglearea(4,2)
ans =
8
>> Rectanglearea([4 2 1],[2 2 1])
ans =
8 4 1
>> Rectanglearea([4;2],[2;1])
ans =
8
2
>> Rectanglearea([4 2 1],2)
ans =
8 4 2
64
MATLAB Function Writing - Examples
Example5: Write a MATLAB function which calculates and outputs the construction cost
of cylinder, make sure that the function accepts the radius, height, and unit cost for
construction (per unit volume). All the three inputs can be scalar values or vectors.
𝑉𝑉 = 𝜋𝜋𝑟𝑟 2 ℎ
𝑡𝑡𝑡𝑡𝑡𝑡𝑡𝑡𝑡𝑡 𝑐𝑐𝑐𝑐𝑐𝑐𝑐𝑐 = 𝑉𝑉 ∗ 𝑐𝑐𝑐𝑐𝑐𝑐𝑐𝑐𝑐𝑐 𝑚𝑚𝑚𝑚𝑚𝑚𝑚𝑚𝑚𝑚 𝑐𝑐𝑐𝑐𝑐𝑐𝑐𝑐
Function:
function [ tc ] = CylCost( r, h, c )
v = r.^2.*h*pi;
tc = v .* c;
end
Command window:
>> CylCost(0.5,3,30)
ans =
70.6858
>> CylCost([.3:.1:.6],3,30)
ans =
25.4469 45.2389 70.6858 101.7876
>> CylCost([.3:.1:.6],[3 3 4 5],30)
ans =
25.4469 45.2389 94.2478 169.6460
65
MATLAB Function Writing - Examples
Example6: The velocity of a falling object can be determined by the equation below.
1. Write a function that represent the velocity equation.
2. Plot the velocity if the mass ranges between 45 to 90kg, assume that the drag coefficient =
0.25kg/m, and the time = 5sec.
3. Plot the velocity for the time ranging from 1sec to 20sec, assume the mass = 65, the drag
coefficient = 0.25kg/m.
4. Determine the object mass that reach a velocity of 26 in 3.5 seconds, assume that the drag
coefficient = 0.25kg/m. Consider a precision of up to one decimal place.
5. Determine the time in which the object will reach the terminal velocity if the mass
= 65kg and, drag coefficient = 0.25kg/m, consider ∆𝑣𝑣 ≤ 0.001 as the termination criteria for
the while loop.
Where:
g: is the acceleration of gravity (9.81 m/s2). m: is the mass (kg). Cd: is the drag coefficient
(kg/m). t: is the time (sec).
66
MATLAB Function Writing - Examples
1. The Function:
Function:
function [ v ] = FallVelocity( m, cd, t)
g
v = sqrt(g*m./cd).*tanh(sqrt(g*cd./m).*t);
end
67
MATLAB Function Writing - Examples
2. Mass Vs. Velocity plot (for m from 45 to 90kg, Cd= 0.25kg/m, and t = 5sec):
68
MATLAB Function Writing - Examples
3. Time Vs. Velocity plot (for t from 1 to 20sec, Cd= 0.25kg/m, and m = 65kg):
69
MATLAB Function Writing - Examples
4. Finding the object mass that reach a velocity of 26m/s in 3.5sec, assuming that
Cd= 0.25kg/m. Consider a precision of up to one decimal place:
In script file:
m = 0;
v = 0;
while v<26
m=m+0.1;
v = FallVelocity(m,0.25,3.5);
end
disp(m);
70
MATLAB Function Writing - Examples
5. Finding the time at which the object will reach the terminal velocity if the m =
65kg and, Cd = 0.25kg/m, considering time increment of 0.1sec and ∆𝑣𝑣 ≤ 0.001 as the
termination criteria for the while loop:
In script file:
t = 0;
v = 0;
vo = inf;
while abs(v-vo)>0.001
vo = v;
t = t + 0.1;
v = FallVelocity(65,0.25,t);
end
disp(t);
71