Mod&Sim Matlab Lect3 Functions Conditional LoopsP1
Mod&Sim Matlab Lect3 Functions Conditional LoopsP1
Lecture 3
Functions
Conditional statements
Loop statements
Example:
4
The Matlab Editor pops up and write your function as :
Delete everything in the Editor and type the following code in the Editor
6
7
To call this function:
8
Many functions do not calculate values, but rather accomplish a task such as
printing formatted output.
Example
Call
since the function isn’t returning any value, it cannot be called from an
assignment statement:
9
A variable that is created within a function has a limited scope. This means
that this variable can be only accessed or modified by this function.
This variable is called a local variable.
Answer:
10
A variable created in the Command Window cannot be accessed by a
function.
Example:
12
13
Syntax
x=1;
y=-4;
r=1;
b=0;
if (x>0 & y<3)
r=3;
b=b-1;
r=2 end
r = 3, b=-1 14
Example:
Write a function that has two arguments and returns a value which is equal to
the addition of both arguments.
This function checks whether both arguments are scalars:
If both arguments are scalars, the function performs the addition;
Otherwise, it displays a warning message and returns without attempting
to perform the addition.
15
16
Syntax
r=2 r=3
17
r=2 r=3
18
Syntax
19
r=2
20
Syntax
21
Suppose that we would like to convert 10 cm to meters.
y = 0.1
22
The expression case {'km', 'kilometer'} means that the command
y=1000*x; is evaluated when units variable is equal to either 'km' or
'kilometer'. 23
24
The for keyword is used to run a piece of code for a specific number of
times.
Syntax
Where . approximates down a real number toward the nearest lower integer
The loop stops executing the commands when the value of the iteration
Variable is greater than the final value.
25
Write Matlab code to generates the first 7 numbers of Fibonacci series
26
>> x
x=0.5314
27
>> x
x=0.5905 28
>> x
x=0.9
29
Matlab will not execute the commands inside the loop since the number of
iterations is negative. The value of ix is [ ] i.e., empty matrix
>> x
x=1
30
−6−6
The number of iterations of a for loop = +1=6+1=7
−2
The values of iteration variable are 6, 4, 2, 0, -2, -4, -6
>> x
x=0.4783
31
You can follow the execution of the program on a step-by-step basis using
the debug tools available in Matlab to check the results for each iteration
32
Try it without
loop
33
Syntax
m: Number of rows
n: Number of columns 34
of Example 19
Try it
without
loop
35
Answer
Try it
without
loop
36
37
38