MATLAB Examples - Flow Control and Loops PDF
MATLAB Examples - Flow Control and Loops PDF
Examples
Flow Control and Loops
−𝑏 ± 𝑏# − 4𝑎𝑐
, 𝑎≠0
2𝑎
𝑐
𝑥= − , 𝑎 = 0, 𝑏 ≠ 0
𝑏
∅ , 𝑎 = 0, 𝑏 = 0, 𝑐 ≠ 0
ℂ, 𝑎 = 0, 𝑏 = 0, 𝑐 = 0
function x = solveeq(a,b,c)
if a~=0
x = zeros(2,1);
x(1,1)=(-b+sqrt(b^2-
4*a*c))/(2*a);
x(2,1)=(-b-sqrt(b^2-
4*a*c))/(2*a);
elseif b~=0
x=-c/b;
elseif c~=0
disp('No solution')
else
disp('Any complex number is a
solution')
end
We test the function: 1
2
3
>> a=0;, b=0;,c=1;
>> solveeq(a,b,c) >> a=0;, b=0;,c=0;
>> solveeq(a,b,c)
No solution Any complex number is a solution
Switch-Case Statements
• Create a function that finds either the Area or the circumference of a
circle using a Switch-Case statement
𝐴 = 𝜋𝑟 #
𝑂 = 2𝜋𝑟
>> r=2;
>> calc_circle(r,1) % 1 means area
>> calc_circle(r,2) % 2 means circumference
We can define the function like this:
function result = calc_circle(r,x)
switch x
case 1
result=pi*r*r;
case 2
result=2*pi*r;
otherwise
disp('only 1 or 2 is legal values for x')
end
k=3;
while f < max
ans =
0 1 1 2 3 5 8
13 21 34 55 89 144 233
For Loops
• Extend your calc_average function from a previous example so
it can calculate the average of a vector with random elements.
Use a For loop to iterate through the values in the vector and
find sum in each iteration:
>> z=calc_average(x,y)
z =
3
The function can be written like this:
function av = calc_average2(x)
mysum=0;
N=length(x);
for k=1:N
mysum = mysum + x(k); Testing the function gives:
end >> x=1:5
x =
1 2 3
av = mysum/N; 4 5
>> calc_average2(x)
ans =
3
If-else Statement
Create a function where you use the “if-else” statement to find
elements larger then a specific value in the task above. If this is
the case, discard these values from the calculated average.
Example discarding numbers larger than 10 gives:
x =
4 6 12
>> calc_average3(x)
ans =
5
The function can be written like this:
function av = calc_average2(x)
mysum=0;
total=0;
N=length(x);
av = mysum/total;
Hans-Petter Halvorsen, M.Sc.
E-mail: [email protected]
Blog: http://home.hit.no/~hansha/