3 matlab training
-
Upload
waleed-usman -
Category
Technology
-
view
398 -
download
6
Transcript of 3 matlab training
3. MATLAB Dr. Kashif Mahmood Rajpoot
SEECS, NUST Islamabad [email protected]
NUST Science Society (NSS) Workshop
Workshop Contents: Session 3
• Conditions: if, else
• Loops: for, while
• Vectorization
• Function: input/output arguments, saving, opening file, naming, calling function
Selection Statements
• Program execution is sequential by default – i.e. top-to-bottom execution of statements
– Statements are executed one after another in a fixed sequential order
– Each statement is executed only once
• Controlling the order in which the instructions are executed – Jump/selection in the order of statements under
some condition (if-else)
If-else • First, the condition is evaluated
– True, action1 is executed – False, action2 is executed
% This script calculates the area of a circle % It error-checks the user’s radius radius = input(‘Please enter the radius: ’); if radius <= 0 fprintf(‘Sorry; %.2f is not a valid radius\n’,radius) else area = 2*pi*(radius^2); fprintf(‘For a circle with a radius of %.2f,’,radius) fprintf(‘the area is %.2f\n’,area) end
If-else
if ( grade >= 60 )
disp(‘Passed’)
else
disp(‘Failed’)
Relational operators • Relational operators – test the “relation”
between two expressions/numbers/letters – Important, note the == symbol for testing the equality – Don’t mix/confuse it with = symbol, which is the
assignment operator
• Relational operators produce logical result of either 1 or 0 – 1 – true – 0 – false
• Can be used with numbers, letters, variables, scalars, vectors, and matrices – For vectors/matrices, the shape and size must match
Logical operators
• Often, to test multiple conditions we can use logical operators like:
– AND (&&), OR (ІІ), NOT (~)
– x>=0 && y>=0
– X>=0 ІІ y >=0
– ~(x>=0)
Operator Precedence
If-elseif • If a condition is false, instead of jumping to an
else we can test alternative conditions by elseif
marks ≥ 80 A
60 ≤ marks < 80 B
marks < 60 F
Logical Functions
• MATLAB built-in functions that perform some logical test
Loops
• Default execution of programs is:
– Top-to-bottom
– Every statement is executed only once
• Loops permit us to execute a code block more than once under a specified condition
– Repeat a code block indefinite number of times, until some condition is met (while loop)
– Repeat a code block definite number of times, i.e. number of repetitions are known in advance (for loop)
for loop
• for loop executes a code block a specified number of times
– index is called the loop variable or loop index
– expr is the loop control expression
– Columns in expr are stored in index and loop is executed once for each column in expr
– expr can also be of the form first:incr:last
for loop
• MATLAB generates control expression
• Program assigns first column to index
• Execute the loop body
• Assign the next column to index
• Again, execute the loop body
• Repeat above step as long as there are any columns left in the control expression vector
Example syntax: for loop
Example: for loop
• Factorial function
Loops – important points
• Loops vs. vector operations
• Since MATLAB is designed for array/vector/matrix operations, it is often possible to perform operations on the entire array
• Vector operations may be significantly faster than loop operations
while loop
• while loop continuously executes a set of statements until the specified condition is met
• Expression is non-zero (i.e., true)
– Code block is executed
– Control returns to while statement
– Re-check the expression
– Continue with execution of code block
– Repeat until expression becomes zero (false)
Functions
• Dividing a task into individual subtasks according to their ‘function’ – E.g., departments of an organization
• Division helps to tackle subtasks easily and efficiently
• Subtasks can then be utilized (& re-used)
• In MATLAB, functions permit us to write each ‘subtask’ as an individual unit that can be ‘called’ from some place in the code
Functions • Special type of m-file
• Runs in its own independent workspace
– This is important: functions can’t access the normal workspace of MATLAB
– Variables in MATLAB’s workspace are not directly accessible by functions
– Variables created by functions are not directly accessible by MATLAB
Functions
• Functions receive input data through input arguments, and return the results through output arguments
• General format of a function is:
function *outarg1, outarg2, …+ = fname(inarg1, inarg2, …)
% comments
Executable code
Functions
• MATLAB’s built-in functions – fprintf, disp, input, sin, cos, mean, std, exp, … – They take input arguments, perform some processing
using that input, and return the results as output arguments
• Note that passing the input arguments and returning the output arguments are not mandatory – i.e., we can write functions that do not accept input
arguments and/or do not return output arguments – E.g., tic, toc, clock, now, whos
Functions • Script vs Function • Script – collection of code placed together in an
m-file – Run by typing the filename – Running a script is same as writing the statements in
MATLAB’s command window – Shares MATLAB’s workspace
• Function – collection of code placed together as a function in an m-file – Run by typing the filename – On calling, we can provide input arguments and get
output arguments – Uses its own private workspace
• Calling a user-defined function – Can be called from MATLAB’s command window
or from a script file or from inside another function
– The function is called/invoked by writing its name
– Will need to provide any mandatory input arguments and receive any returned output arguments
• Example – dist2.m – distance between 2 points
– test_dist2.m – test the distance function
Functions
Variable passing: Pass-by-value
• MATLAB programs communicate with functions using a pass-by-value scheme
• On a function call, the input arguments are passed by copying their value into new variables inside the function
– i.e., any modification inside the function does not affect the variables outside the function
Example: coordinate system