Graphics Programs Reference
In-Depth Information
y = ones(size(x));
for n = 1:prod(size(x))
if x(n) ~= 0
y(n) = sin(x(n))/x(n);
end
end
Above the loop we added a block of four lines whose purpose is to make the
M-file run faster if all the elements of the input x are nonzero. The difference
in running time can be significant (more than a factor of 10) if x has a large
numberofelements.Hereishowthenewblockoffourlinesworks.Thefirst if
statement will be true provided all the elements of x are nonzero. In this case,
wedefinetheoutput y usingMATLAB'svectoroperations,whicharegenerally
much more efficient than running a loop. Then we use the command return
to stop execution of the M-file without running any further commands. (The
use of return here is a matter of style; we could instead have indented all of
the remaining commands and put them between else and end statements.)
If, however, x has some zero elements, then the if statement is false and the
M-file skips ahead to the commands after the next end statement.
Often you can avoid the use of loops and branching commands entirely by
using logical arrays. Here is another function M-file that performs the same
task as in the previous examples; it has the advantage of being more concise
and more efficient to run than the previous M-files, since it avoids a loop in
all cases:
function y = f(x)
y = ones(size(x));
n=(x~=0);
y(n) = sin(x(n))./x(n);
Here n isalogicalarrayofthesamesizeas x witha 1 ineachplacewhere x has
a nonzero element and zeros elsewhere. Thus the line that defines y(n) only
redefines the elements of y corresponding to nonzero values of x and leaves
the other elements equal to 1 . If you try eachof these M-files withan array of
about 100,000 elements, you will see the advantage of avoiding a loop!
Branching with switch
The other main branching command is switch . It allows you to branchamong
several cases just as easily as between two cases, though the cases must be de-
scribed through equalities rather than inequalities. Here is a simple example,
which distinguishes between three cases for the input:
Search WWH ::




Custom Search