Graphics Programs Reference
In-Depth Information
One way to make this M-file work for vectors and matrices is to use a loop
to evaluate the function element-by-element, with an
if
statement inside the
loop:
function y = f(x)
y = ones(size(x));
for n = 1:prod(size(x))
if x(n) ~= 0
y(n) = sin(x(n))/x(n);
end
end
In the M-file above, we first create the eventual output
y
as an array of ones
with the same size as the input
x
. Here we use
size(x)
to determine the
number of rows and columns of
x
; recall that MATLAB treats a scalar or a
vector as an array withone row and/or one column. Then
prod(size(x))
yields the number of elements in
x
.Sointhe
for
statement
n
varies from
1
to this number. For each element
x(n)
, we check to see if it is nonzero, and
if so we redefine the corresponding element
y(n)
accordingly. (If
x(n)
equals
0
, there is no need to redefine
y(n)
since we defined it initially to be
1
.)
We just used an important but subtle feature of MATLAB, namely that
eachelement of a matrix can be referred to witha single index; for example,
if
x
isa3
×
2 array then its elements can be enumerated as
x(1)
,
x(2)
,
...
,
x(6)
. In this way, we avoided using a loop within a loop. Similarly, we could
use
length(x(:))
in place of
prod(size(x))
to count the total number of
entries in
x
. However, one has to be careful. If we had not predefined
y
to have
the same size as
x
, but rather used an
else
statement inside the loop to let
y(n)
be
1
when
x(n)
is
0
, then
y
would have ended up a 1
×
6 array rather
than a 3
×
2 array. We then could have used the command
y = reshape(y,
size(x))
at the end of the M-file to make
y
have the same shape
as
x
. However, even if the shape of the output array is not important, it is
generally best to predefine an array of the appropriate size before computing
it element-by-element in a loop, because the loop will then run faster.
Next, consider the following modification of the M-file above:
function y = f(x)
ifx~=0
y = sin(x)./x;
return
end
Search WWH ::
Custom Search