23.06.2015 Views

MATLAB Programming

MATLAB Programming

MATLAB Programming

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

12 <strong>Programming</strong> Tips<br />

Using switch Versus if<br />

It is possible, but usually not advantageous, to implement switch-case<br />

statements using if-elseif instead. See pros and cons in the table.<br />

switch-case Statements<br />

Easier to read.<br />

Can compare strings of different<br />

lengths.<br />

Test for equality only.<br />

if-elseif Statements<br />

Can be difficult to read.<br />

You need strcmp to compare strings<br />

of different lengths.<br />

Test for equality or inequality.<br />

<strong>MATLAB</strong> case Evaluates Strings<br />

A useful difference between switch-case statements in <strong>MATLAB</strong> and C is<br />

that you can specify string values in <strong>MATLAB</strong> case statements, which you<br />

cannot do in C.<br />

switch(method)<br />

case 'linear'<br />

disp('Method is linear')<br />

case 'cubic'<br />

disp('Method is cubic')<br />

end<br />

Multiple Conditions in a case Statement<br />

You can test against more than one condition with switch. Thefirstcase<br />

below tests for either a linear or bilinear method by using a cell array<br />

inthecasestatement.<br />

switch(method)<br />

case {'linear', 'bilinear'}<br />

disp('Method is linear or bilinear')<br />

case ()<br />

end<br />

Implicit Break in switch-case<br />

In C, if you don’t end each case with a break statement, code execution falls<br />

through to the following case. In <strong>MATLAB</strong>, case statements do not fall<br />

12-40

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!