Lecture 3: Programming
Prof. Dr. Salina A.
Samad
Mr. Iskandar Yahya
Programming
Matlab script files is a text file that contains
sequence of matlab commands, saved as an
“M-file”.
Its like typing a series of command on the
matlab prompt window, except that you don’t
have to type the commands over and over
again if u want to use it.
You can just “call” the file and the desired
output will be given to you.
Let’s create an M-file. Click “file>new>M-file”.
An editor/debugger window will open.
We can start typing our commands now.
Programming
Example:
Programming
Save the file with extension “.m”. Even if u
write the script in a different text editor
program (which is possible), u must save it
with “.m” extension file.
Here let’s save it as “testscript.m”.
Pay attention to the directory you are saving
your file. Its best to save it under the directory
that is currently accessed by your matlab
program. Please check.
Usually its “D:\MATLAB….\work”.
Now click “save” and name it as
“testscript.m”
Exit the editor window and return to MATLAB
Programming
The program executes:
>> testscript
This is an example of a script file.
a = 15.708, C is a string variable. C = Testing String.
Sometimes there will be an error message:
>> newscript
??? Undefined function or variable 'newscript'.
The script file doesn’t exist, or the directory you
saved the file is not on matlab’s search path.
Reconfigure your path by clicking “file” and
choose “set path”. Add the appropriate folder to
your matlab’s search path.
Control Flow
We will now see the common “control
structures” –
In C programming –Syntax
Assembly – Mneumonic/ instruction set
Common “control structures”:
if-end, if-else-end, if-elseif-else-end, switch-
case, for, and while.
Control Flow
IF-END
IF used to test condition and execute a block of
instructions if the condition is true.
If (condition)
statement 1;
statement 2;
statement 3;
end
If a condition has a numeric value of 1, or is
true, the statements between the if and end
keywords will be executed.
If it is false, or returns the value 0, then all the
instructions/statements between if and end is
skipped and resume at the line after end.
Control Flow
IF-END
The conditions can be mathematical relation
operator
Greater than (>)
Greater than or equal to (>=)
Less than (<)
Less than or equal to (<=)
Equal to (==)
Not equal to (~=)
E.g. if( A >= 2*pi)
statement 1;
statement2;
end
Control Flow
IF-END
The conditions can also be a logical operator, or
combination of logical and mathematical
Logical AND (&) – (a>b) & (x<5)
Logical OR (|) – (x~=5) | (y<=1)
True if the result of a condition is false, and false if
the result of condition is true. (~) typed before the
condition statement bracket. - ~((a>b) | (x<5))
Exclusive OR (xor) – xor((x>2), (y == 5))
Use the “%” symbol to add comments on your
program. This comments will not be executed.
Now let’s try and write our own program!
Control Flow
Example program – Guessing Game.
%
% This is file guess01.m
%
real_number=rand(1); % Generate a number between 0 and 1
real_number+10*real_number; % Scale the number between 0 and 10
number=ceil(real_number); % Round the number to the next highest
integer.
% Ask the user to guess the number:
fprintf('I am thinking of a number between 1 and 10. \n');
guess = input('Guess a number: ');
% Test the number.
if guess == number
fprintf('Congratulations - You guessed the correct number. \n');
end
if guess ~= number
fprintf(‘Haha! Your guess was wrong.\n');
fprintf('The number i was thinking of was %g. \n');
end
Control Flow
Example program – Guessing Game.
>> guess01
I am thinking of a number between 1 and 10.
Guess a number: 5
Haha!. Your guess was wrong.
The number i was thinking of was 1.
Try to understand what each line of the
program is doing. Some predefined or built-in
functions was used.
Try to “Help” it and learn.
Control Flow
IF-ELSE-END
If a condition has a numeric value of 1, or is
true, the statements between the if and else
will be executed, then skip to end.
If it is false, or returns the value 0, then all the
instructions/statements between else and end
is executed and resume at the line after end.
E.g:
if ( A == 2)
statement 1;
else
statement 2;
end
Control Flow
IF-ELSEIF-END
A powerful form of if statement.
An if-else-end only provides one option if the
if condition is not true (returns value 0).
if-elseif-end on the other hand provides more
options for other conditions. Let’s look at an
example for clarification.
E.g: if (command == 1)
statement 1;
elseif (command == 2)
statement 2;
elseif (command == 3)
statement 3;
else
fprintf(‘Invalid command entered. \n’);
end
Control Flow
SWITCH-CASE
Used to test whether an expression is equal to
a number of different values. It may not be able
to check for most conditions, (a >= 5)
E.g: command = input(‘Specify your command [1-5]: \n’)
switch command
case 1
statement 1;
case 2
statement 2;
case {3,4,5}
fprintf(‘Your chose either option 3,4 or 5.’)
statement 3;
otherwise
fprintf(‘Error! – Please choose 1 – 5 only!’)
end
Control Flow
FOR loops and BREAK
Used to execute a set of statements (m) a
particular number of times (n).
E.g.: for i = 1:10
statement 1;
statement 2;
statement 3;
statement m;
end
In the example, “i” is set to “1”, and all m
statements are executed. Then “i” is set to 2,
and all the statements are executed again. This
process goes on until i = 10. After this, program
will run instructions below “end”.
Control Flow
FOR loops and BREAK
“Break” is used to get out of the loop after a
certain condition is satisfied without finishing the
“for” loops.
E.g:
fprintf(‘Guess a number, you have 10 guesses. \n);
number = 3; correct = 0;
for i = 1:10
guess = input(‘Type a number: ’);
if guess == number
fprintf( ‘\n Congrats! – your guess is correct!’);
correct = 1;
break;
else
fprintf(‘your guess is wrong – guess again. \n’);
end
if ~ correct
fprintf(‘The number I was thinking was %g. \n’, number);