90 likes | 223 Vues
This guide covers the fundamentals of branching statements in MATLAB, including the use of `switch`, `case`, and `otherwise`. It explains how to evaluate expressions and execute corresponding statements based on conditional checks, with examples for clarity. The section further illustrates the concept of plotting multiple graphs in a single window using `subplot`, providing practical examples for sine, cosine, and exponential functions. Resources for further learning are also included, such as recommended reading materials and lecture slides.
E N D
Branching statements • If • Switch
switch, case, otherwise end Let VAL be value of expression. Assume VAL is a scalar double. switch expression case testval1 statements1 case testval2 statements2 otherwise statementsOther end • Does VAL equal testval1? • Yes: Execute statements1 • Jump past end. • No: • Does VAL equal testval2? • Yes: Execute statements2 • Jump past end • No: • Execute statementsOther • Jump past end • Move to code beyond end Any number of cases are allowed. There does not have to be an otherwise (and associated statements).
switch, case, otherwise end VAL (the value of expression) need not be a scalar double. It can also be a char array. Matlab uses strcmp (string compare) to check equality of VAL to the various testval1, testval2, etc. switch expression case testval1 statements1 case testval2 statements2 otherwise statementsOther end
switch, case, otherwise end switch expression case testval1 statements1 case value2 statements2 otherwise statementsOther end testvalcan also be cell arrays.The equality of VAL (value of expression) is tested for any of the contents of the cell array testval.
Switch example if x == 1 fprintf('One'); elseifx == 2 fprintf('Two'); elseifx == 3 fprintf('Three'); else fprintf('%d', x); end switch x case 1 fprintf('One'); case 2 fprintf('Two'); case 3 fprintf('Three'); otherwise fprintf('%d', x); end
More plots • Subplot: putting multiple plots in one window x=0:.1:2*pi;subplot(2,2,1);plot(x,sin(x));subplot(2,2,2);plot(x,cos(x));subplot(2,2,3)plot(x,exp(-x));subplot(2,2,4);plot(peaks);
Resources • “Introduction to Programming with Matlab”, J. Michael Fitzpatrick and John D. Crocetti • Lecture slides E77, Andy Packard, http://jagger.me.berkeley.edu/~pack/e77