2. mod(X,Y) rem(X,Y)
• Returns the remainder of X and
Y
• mod (x,0) =x
• mod retains the sign of Y
x mod y
11 mod 5 = 1
-11 mod 5 = 4
11 mod -5 = -4
-11 mod -5 = -1
• Returns the remainder of X and
Y
• rem(x,0)=NaN
• rem retains the sign of X
x rem y
11 rem 5 = 1
-11 rem 5 = -1
11 rem -5 = 1
-11 rem -5 = -1
George Iskander - ITI 2
Mathematical operation
3. Matrix Indexing
• B = A(1,1) B = 1
• C = A(2,3) C =2
• D = A(6) D =9
• E = A(1, [1,2,3] ) A( 1st Row, Columns: 1,2 and 3) = 1 3 7
• F = A(1, : ) similar to A(1,1:3) = 1 3 7
• G = A(3 , 4) A(3rd Row, 4th Column) Index exceeded matrix dimensions)
• H = A( [1,3] , : ) A(Rows: 1 & 3 , All Columns) = [1 3 7; 8 90]
• I = A(: , : ) A(All Rows, All Columns) = [1 3 7; -5 4 2; 8 90]
• J = A(end,2) A(Last Row,2) = 9 3
6. Eigen Values and Eigen Vectors
Definition: A scalar λ is called an eigenvalue of the
matrix A(n*n) where it is a nontrivial solution of A𝑥 = λ 𝑥.
Such 𝑥 is called an eigenvector corresponding to the
eigenvalue λ.
A 𝑥 = λ 𝑥
A 𝑥 − λ 𝑥 = 0
A 𝑥 − λI 𝑥 = 0
(A − λI) 𝑥 = 0
det( A − λI) =0
Characteristic Equation of a system
Checkeig(A)
6
7. For a multidimensional array
• Enter a 3D matrix:
– >> x = [1 2 3; 4 5 6; 7 8 9];
– >> x(:,:,2) = x’;
• Check sum(x,1), prod(x,2) and mean (x,3)
>> y = sum(x,1) >> y = prod(x,2) >> y = mean(x,3)
y(:,:,1) =
12 15 18
y(:,:,2) =
6 15 24
y(:,:,1) =
6
120
504
y(:,:,2) =
28
80
162
y=
1 3 5
3 5 7
5 7 9
size(y) = 1 3 2 size(y) = 3 1 2 GesoirzgeeI(syka)nd=er3-I3TI 7
8. A < B
A <= B
A > B
A >= B
A == B
A ~= B
• Returns a logical array
8
9. • Logical Values:
– Any nonzero value MATLAB consider as TRUE
– Zero value MATLAB consider as FALSE
– MATLAB always returns 1 as TRUE and 0 as FALSE
• Short Circuit
• && and || accept scalar values only. For Conditions
• For arrays (element-wise) & (and(A,B)) and | (or(A,B))
check >> 1.4 < sqrt(2) & [pi > 3 -1 > 1] Scalar with vector
• xor(A,B) , not(A)
9
10. • MATLAB Fundamentals
• Programming with MATLAB
• MATLAB Toolboxes “Control Toolbox – Symbolic Toolbox”
• Simulink
• Data Type, Plotting and Fitting, Logical Index
• Introduction to GUI
• Extra :
Connecting Hardware with Matlab
Linking Matlab, Labview and Solidworks 10
11. • Input and Output Commands
Text Interface
GUI Interface
• Programming with MATLAB
M-file script and MATLAB function
• Control Flow
If condition
Switch condition
For loop
While loop
• Polymorphismic Function
• Comment and Sections
11
12. Text Interface
• input() Request user input
>> prompt = ‘Enter the description of the required input’
>> result = input(prompt) the input is stored as it is entered
>> str = input(prompt,'s') the input is stored as a string
• If you press the Return key without entering anything, then input returns an empty
matrix.
12
13. Text Interface
• disp() – display() :
disp(X) displays the X array, without printing thearray name. It 's the same as you
write a statement without semicolon except that empty arrays don't display.
display(X) it differs from disp() that it displays the name of thevariable
• MATLAB invokes the built-in display() when MATLAB executes a statement that
returns a value and is not terminated with a semicolon.
• MATLAB invokes the built-in disp function when the built-in display function calls
disp.
13
14. Text Interface
• fprintf()
It is mainly used to write data to a file but we can use it to write to the screen directly. With
addition property to control the format specification.
fprintf(FORMAT,A1,...,An) formats data and displays the results on the screen.
FORMAT is a string that describes the format of the output fields, and can include
combinations of the following:
* Literal text to print.
* Escape characters, including: b Backspace ‘ ‘ Single quotation mark
f Form feed %% Percent character
n New line Backslash
r Carriage return t Horizontal tab
14
15. Text Interface
• fprintf()
*Conversion specifications, which include a % character, a conversion character (such
as d, i, o, u, x, f, e, g, c, or s), and optional flags, width, and precision fields.
• Towrite on a file fopen(), fclose() are used
– fprintf(fileid, format, A1,…,An)
15
16. Text Interface
• error()
Similar to fprintf; where a message in red appear on the command window as the
default error message that is done by MATLAB and the code is terminated
>> error('nX must be at least %4.2f mmn',5.634)
X must be at least 5.63 mm
Check the difference with warning()
16
17. GUI Interface
• inputdlg()
prompt = {'Enter your name:', 'Enter your age:'};
titlename =‘Personal Information';
numlines=1;
default={‘Mahmoud Hussein',‘25'};
ANSWER = inputdlg(prompt, titlename, numlines, default)
Example 2:
x = inputdlg({'Name','Telephone',’Address’,'Account'}, …
'Customer Information ', [1 50; 1 12;2 50; 1 7])
Output is stored
in cell array
17
18. GUI Interface
• menu()
choice = menu('mtitle','opt1','opt2',...,'optn')
choice = menu('mtitle',{'opt1','opt2',...,'optn‘})
Example:
choice = menu('What is your department?', 'Java ', 'Mechatronics', 'GIS')
Output is integer
refering to the order
of your choice
18
19. GUI Interface
• questdlg()
button = questdlg('qstring','title') By default (the choices are Yes, No and Cancel)
button = questdlg(‘Is the course useful? ',‘Feedback',‘Yes',‘No', ‘May be‘, ‘Yes’)
Output is a
string similar to
your choice
19
21. GUI Interface
•msgbox()
msgbox(message, title, icon)
message=‘Help me’
title = Help
icon= 'help‘ % It can be 'none', 'error', 'warn' or 'help'. The default is 'none'
• errordlg()
errordlg(message, title)
• waitbar(x) x varies from 0 to 1
Check warndlg(), helpdlg()
21
22. George Iskander - ITI 22
• Any command written
directly on the
command window
• Directly processed
and the output will
directly appear on the
command window
23. • Any command written
directly on the
command window
• Directly processed
and the output will
directly appear on the
command window 23
24. M-file Script
• A group of statements that are processed in sequence altogether.
• These statements do a certain function.
• No argument can be passed to the M-file before running
• Has direct effect on the workspace
• Before running the script, it must be save in an m-file *.m
Conditions for choosing m-file name: Calling the script
• Refers to the function of the script
• Same as variables
• Be sure no overlap with other
built-in function. Check exist()
• Press Run on the editor toolbar
• Write the name of the m-file
directly on the command window
• Can be called inside other script
24
25. M-file Script
• Example 1:
• Write an M-file that:
– Plot a given function from user
– Plot it’s derivative
– Plot it’s integration
– Identify the peaks and valleys of the main function
• Used functions : cumtrapz() – plot() – text() – gtext() – title()
25
27. M-file Script
• Example 2:
• Write an M-file that:
– Plot a given function from user
– Perform a limit integration according to the user input
• Used functions : trapz() – area() – ginput()
27
28. MATLAB Function
• A group of statements that are processed in sequence altogether.
• The first sentence must declare that the script is a function. Specify the inputs,
outputs and the name of the function.
• Argument can be passed to the function while calling it as well as assigning variables
for outputs based on the prototype
• Has its own workspace, (different scope)
• Before running the function, it must be save
in an m-file *.m with the same name of the
function (same rules)
Calling the Function
• Press Run on the editor toolbar ,if
no required arguments
•Write the name of the function
directly on the command window
• Can be called inside other script
28
29. MATLAB Function
•Example 1:
function myRand
a= 5+rand(3,4)*2
end
1- We need a variable to hold the output of the function
• Example 2:
function a = myRand
a= 5+rand(3,4)*2;
end
Activity 1: Check the value of
• max(round(a))
• min(round(a))
• max(fix(a))
• min(fix(a))
You can find the
variable ‘a’ in the
workspace
29
30. MATLAB Function
2- We need to declare variables to pass input to the function
• Example 3:
function a = myRand (low,high)
a= low+rand(3,4)*(high-low);
end
3- General form (accept no. of rows and coloums and the range)
• Example 4:
function a = myRand(row,col,low,high)
a= low+rand(row,col)*(high-low);
end
The order of the input
is very important
30
31. MATLAB Function
4- We can have more than one output
• Example 5a:
function a = myRand(row,col,low,high)
a = low+rand(row,col)*(high-low);
a(end+1,end+1) = sum(a(:));
end
Example 5b:
function [a, sumno] = myRand(row,col,low,high)
a = low+rand(row,col)*(high-low);
sumno = sum(a(:));
end
Compare
both
functions
31
32. MATLAB Function
5- We can have more than one function
• Example 6:
function [a, sumno] = myRand(row,col,low,high)
a = low+rand(row,col)*(high-low);
sumno = sumelements(a(:));
end
function x = sumelements(mat)
x = sum(mat(:));
end
Run it step by
step and check
the change in
workspace
32
35. Build the following function
1. Write a function called odd_index that takes a matrix, M, as input argument and
returns a matrix that contains only those elements of M that are in odd rows and
columns. Note that both the row and the column of an element must be odd to be
included in the output.
2. Write a function called int_col that has one input argument, a positive integer n
that is greater than 1, and one output argument v that is a column vector of length
n containing all the positive integers from 1 to n, arranged in such a way that no
element is equal to its own index value.
3. Write a function called pitty that takes a matrix called ab as an input argument. The
matrix ab has exactly two columns. The function should return a column vector c
that contains (a^2 + b^2)^0.5 = c,
35
36. • if loop
• switch case
• for loop
• while loop
• try and catch
36
37. if Loop
• If the condition is true , a group of commands are executed,
otherwise we jump to complete the rest of the program
if (condition)
--------
--------
end
Commands
Yes
37
No
38. if - else Loop
• If the condition is true , a group of commands are executed,
otherwise another group of commands are executed then
the rest of the program is completed normally
if (condition)
--------
--------
else
--------
--------
end
Commands
38
Yes
No
Commands
39. Nested if Loop
• If- elseif – else statement
if (condition)
--------
--------
elseif (condition)
--------
--------
else
--------
--------
end
Commands
Yes
No
Commands Commands
Yes
No
Until the first
39
conditionis
true
40. switch case
• Check the value of a variable, if it is equal to a certain
value (case), the commands below it will be executed.
• If no case is correct, a default block may be added at the
end with a key word called otherwise
switch x
case 1
--------
case 2
--------
case 3
--------
otherwise
--------
end
Commands
Commands
Commands
Commands
Yes
No
Yes
No
Yes
No
In case you
want more
than one value
in a case use { }
40
41. for Loop
• When you need to repeat a certain steps for a known
number of times
for i = 1:n
--------
--------
end
This loop will be repeated length of i times
• A very strong feature that it can have variable step also it
can be a cell array with different data types
i= {‘hi’, *1:5], 3, [1:3;4:6]}
Intialize
Commands
update
Yes
No
41
42. while Loop
• We you need to repeat a certain steps as long as a certain
condition is true
while (condition)
--------
--------
end
Commands
Yes
No
42
43. break – continue - return
43
• break : Terminate execution of WHILE or FOR loop.
– It will end the specified loop, will not complete the rest of iteration. If nested
loops, will terminate the innermost loop only
• continue : Pass control to the next iteration of FOR or WHILE loop without
completing the current iteration, skipping any remaining statements in the body
• return : when executed it returns to the invoking function
– Normally functions return when the end of the function is reached. But a return
statement can be used to force an early return.
44. try and catch
Type 1: Type 2: Explaination
try
--------
--------
end
If error occurred the
rest of the loop will
not be completed
without an error
message
try
--------
--------
catch ME
--------
--------
end
• The statements
between the try and
catch are executed.
However, if an error
occurs while execution,
the error is captured
into an object, ME
(optional) and the
statements between
the CATCH and END
are executed.
44
45. Try and catch
>> A=input(‘Matrix=’);
>>try
>>B=inv(A);
>>catch
>>msgbox(‘matrix is not aquare’)
>>end
46. General Form
• How to make our myrand function a polymorphism?
• nargin a variable that holds the number of input argument
• nargout a variable that holds the number of output argument
• Implement it on myRand function to be generic function
46
47. Variable I/P and Variable O/P
• How to make a function that can have variable number of input or output?
• function [s, varargout] = myfun(x, varargin)
– varargin : Allows any number of arguments to a function. The variable
varargin is a cell array containing the optional arguments to the function. It must be
declared as the last input argument and collects all the inputs from that point
onwards.
– varargout : Allows any number of arguments out of a function. The variable
varargin is a cell array containing the optional arguments of the function. It must
be declared as the last output argument and must contains all the outputs after
that point onwards
47
48. % Toadd a comment. Anything after it will be ignored
% If you write it under a declared function immediate , it will be the help of your
function when you the user will ask for help
%% In M-file, to run a separate part.
48