Lab # 3 15th Feb.
2014
Flow Control EVAL Command Matlab Calling Priority Input and output techniques File input/output Function (User Defined Functions)
Logic Control: Iterative Loops:
FOR WHILE IF / ELSEIF / ELSE SWITCH / CASE / OTHERWISE
Works on Conditional statements Short-circuited in MATLAB once a condition is true, the sequence terminates.
if I == J A(I,J) = 2; elseif abs(I-J) == 1 A(I,J) = -1; else A(I,J) = 0; end
if_examp
More efficient than elseif statements Only the first matching case is executed
switch input_num case -1 input_str = 'minus one'; case 0 input_str = 'zero'; case 1 input_str = 'plus one'; case {-10,10} input_str = '+/- ten'; otherwise input_str = 'other value'; end
switch_examp
Similar to other programming languages Repeats loop a set number of times (based on index) Can be nested
N=10; for I = 1:N for J = 1:N A(I,J) = I+J; end end
for_examp
Similar to other programming languages Repeats loop until logical condition returns FALSE. Can be nested.
I=1; N=10; while I<=N J=1; while J<=N A(I,J)=1/(I+J-1); J=J+1; end I=I+1; end
while_examp
Using Array Operations:
Density = Mass(I,J)/(Length.*Width.*Height);
Using Loops: [rows, cols]
= size(M);
for I = 1:rows
for J = 1:cols Density(I,J) = M(I,J)/(L(I,J)*W(I,J)*H(I,J)); end
end
array_vs_loops
Evaluates the MATLAB expression specified by
the input string. Very useful for inserting indices into strings.
% This file creates the first N magic matrices.
% Each matrix is saved as a variable: "magic#".
N = 10; abcd = abcd;
for I = 1:N
eval([abcd, num2str(I),]); end eval_examp
High
variable built-in function subfunction private function MEX-file P-file M-file
cos='This string.'; cos(8) ans = r clear cos cos(8) ans = -0.1455
Low
Data Input
Data Input: Three methods 1. Assign data to variables through an assignment statement 2. Input data from Keyboard 3. Read data from a file stored in computer memory
1.
Assign data to variables through an assignment statement
>>x=2; >>y=34.2; >>name= Ahmed; or >>x=2; y=34.2; name=Ahmed;
2.
I. II. III.
IV.
Input data from Keyboard (Interactive input) Input Function Keyboard Command menu function pause command
I. Input Function : See different version of this function >>Enter radius in mr=input(Enter radius in meters:) r=input(Enter radius in meters:); eters:56 %r will become integer r= 56 Enter radius in meters: ninety six %r will become string , Note: r= ninety six >>r=input(what is your Brotehrs name:, s) %r string, what is your fathers name: Ahmed % Note: not required r= Ahmed
compulsory
II. Keyboard & return command keyboard command when included in a script file returns control to the keyboard at the point where command occurs. The command window prompt is prefixed by the letter k. This command is used for 1. Check the intermediate results in the program 2. Make changes in variables value if required 3. Add new MATLAB commands in the program
Example
A=10; B=16; keyboard Z=A-B
%check the value of Y and change Y=10, after finishing write
%return command, it will execute rest program
III. menu function for pictorial selection. Syntax is I=menu(title, option1, option2,..) i=menu('Select the type of load for 8 m simply supported beam', 'Point Load 10 kN','Point Load 20 kN', 'UDL 2 kN /m', 'UDL 4 kN /m'); if i==1 disp('Moment At Center of Beam = 20 kN.m') elseif i==2 disp('Moment At Center of Beam = 40 kN.m') elseif i==3 disp('Moment At Center of Beam = 16 kN.m') elseif i==4 disp('Moment At Center of Beam = 32 kN.m') end
IV. pause command pause command temporarily halts the current computation and waits for the user to give a command to resume the computations. Pressing any key resumes the computation. pause(k) command stops the computation for k seconds. Exp: Make a .m file for the following code and run it P=[1 2; 3 4]; Q=[5 5; 7 8]; disp('The matrix P is given as:') disp(P) disp('Program is paused, please press any key to display matrix Q') pause disp('The matrix Q is given as:') disp(Q) Z=P+Q; disp('Program is paused, please press any key to display sum of P & Q') pause disp(Z) disp('Again program is pausing for 5 sec') pause(5)
Data Input - simplest method
load command
Ex: load(data_file.txt) reads on a row-by-row basis data values separated by spaces or commas and rows
terminated by new line columns must have the same number of elements data is stored in workspace in an array with same name as the argument used in the load function Ex. Portland International Airport monthly rainfall
load (PDXprecip.dat) % must be in search path!
Data Output - simplest method
Save command
Ex: save(data_file_name) Saves all the variables into a .mat file named data_file_name Many other commands are available for special
purpose file I/O
% read data into PDXprecip matrix load('PDXprecip.dat'); % copy first column of PDXprecip into month month = PDXprecip(:,1); % and second column into precip precip = PDXprecip(:,2); % plot precip vs. month with circles plot(month,precip,'o'); % add axis labels and plot title xlabel('month of the year'); ylabel('mean precipitation (inches)'); title('Mean monthly precipitation at Portland International Airport');
Display contents of working directory Practice following in Matlab
dir A = dir size(A) A(3).name
filename = A(3).name
Core MATLAB (Built-in) Functions
sin, abs, exp, ...
MATLAB-supplied M-file Functions
mean, stat,
User-created M-file Functions
?????
Differences between Script & Function M-files:
Structural Syntax Function Workspaces, Inputs & Outputs
Function (subroutine, method, procedure, or subprogram) is a portion of code within a larger program, which performs a specific task and can be relatively independent of the remaining code.
One M-file, One Task, One Workspace
23
Input (Object / Data): X =
80 90 95 100 98 88 92
Functions:
y = mean(x) y = sum(x) y = max(x)
Output: (Data)
91.85
643
100
24
Output
function
Input
It hides the code and its workspace and communicates with the world using the input and output variables
25
A function is a black box
25
The file is a Matlab function The output variables (if there are few use []: [out1 out2] ) Should be same as the name of the file
sumTwoNums.m:
function my_sum = sumTwoNums(a,b) my_sum = a+b; Assign the output variables (else - Matlab will give an error)
26
The input variables
help:
Usage Input
Output
Examples Testing for proper variables
27
function my_sum = sumTwoNums(a,b) First line % SUMTWONUMS sum to scalars % this function sums two scalar % and returns the result % INPUT: % a - the first scalar % b - the second scalar % % OUTPUT: % my_sum - the sum of a and b; sum = a+b if (~isscalar(a)) error('First argument is not a scalar'); end if (~isscalar(b)) error('Second argument is not a scalar'); end
my_sum = a+b;
Calculations and Output assignment
Assume we wrote the function: function my_sum = sumTwoNums(a,b) my_sum = a + b; In the workspace we run:
a b x y s = = = = = 1; 2; 3; 4; sumTwoNums(x, y)
Matlab Workspace: Function Workspace:
a=1 b=2
a=3 b=4 my_sum = 7
What is the output? s = 7
28
X=3
y=4 s=7
A method to solve complex problems Principles:
Start from large problems to small A function does one task Think before you code
29
Keyword: function
Function Name (same as file name .m) Input Argument(s)
Output Argument(s) function y = mean(x)
% MEAN Average or mean value. Online Help % For vectors, MEAN(x) returns the mean value. % For matrices, MEAN(x) is a row vector % containing the mean value of each column. [m,n] = size(x); MATLAB Code if m == 1 m = n; end y = sum(x)/m; output_value = mean(input_value)
Command Line Syntax
Multiple Input function r = ourrank(X,tol) Arguments ( , ) % OURRANK Rank of a matrix s = svd(X); if (nargin == 1) Multiple Output tol = max(size(X))*s(1)*eps; Arguments [ , ] end r = sum(s > tol); function [mean,stdev] = ourstat(x) % OURSTAT Mean & std. deviation [m,n] = size(x); if m == 1 m = n; end mean = sum(x)/m; stdev = sqrt(sum(x.^2)/m mean.^2); RANK = ourrank(rand(5),0.1); [MEAN,STDEV] = ourstat(1:99);