23.06.2015 Views

MATLAB Programming

MATLAB Programming

MATLAB Programming

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

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

are useful when you want to evaluate a statement only when certain<br />

conditions are satisfied.<br />

In this example, <strong>MATLAB</strong> does not execute the function myfun unless its<br />

M-file exists on the current path.<br />

comp = (exist('myfun.m') == 2) && (myfun(x) >= y)<br />

For more information: See “Short-Circuit Operators” on page 3-25 in the<br />

<strong>MATLAB</strong> <strong>Programming</strong> documentation.<br />

Changing the Counter Variable within a for Loop<br />

You cannot change the value of the loop counter variable (e.g., the variable<br />

k in the example below) in the body of a for loop. For example, this loop<br />

executes just 10 times, even though k is set back to 1 on each iteration.<br />

for k = 1:10<br />

disp(sprintf('Pass %d', k))<br />

k = 1;<br />

end<br />

Although <strong>MATLAB</strong> does allow you to use a variable of the same name as the<br />

loop counter within a loop, this is not a recommended practice.<br />

12-34

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

Saved successfully!

Ooh no, something went wrong!