Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
2014
Flow Control EVAL Command Matlab Calling Priority Input and output techniques File input/output Function (User Defined Functions)
Works on Conditional statements Short-circuited in MATLAB once a condition is true, the sequence terminates.
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
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
= 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
for I = 1:N
eval([abcd, num2str(I),]); end eval_examp
High
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.
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
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)
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!
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
% 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');
filename = A(3).name
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.
Functions:
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
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
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;
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
X=3
y=4 s=7
Start from large problems to small A function does one task Think before you code
29
Keyword: function
% 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)
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);