MATLAB return of vector function with IF statement

2019-02-25 03:09发布

问题:

I am calling a self written function 'func' of a vector like this:

x_values=[0 1 2];
result=func(x_values);

The problem is that in this function i have an if statement to determine the ouput. If I apply this function to a scalar, I have no problem, but if I apply it to a vector of numbers, the if statement doesn't do his job. why? And how can i repair it?

function [y]=func(x)
if(x==0)
  y=0
else
  y=1./sin(x);
end
end

回答1:

You need to treat the zero and non-zero entries separately. This is easily achieved via indexing:

function [y]=func(x)
xIsZero = x==0;

%# preassign y
y = x;

%# fill in values for y
y(xIsZero) = 0

y(~xIsZero) = 1./sin(x(~xIsZero))


回答2:

The answer is explained in the help document of IF:

An evaluated expression is true when the result is nonempty and contains all nonzero elements (logical or real numeric). Otherwise, the expression is false.

Conclusion: either add a for loop, or find a better way to vectorize your expression



回答3:

You want to assign only a subset of the vector. For example:

function [y]=func(x)
    y=zeros(size(x));
    mask = x ~= 0;
    y(mask) = 1 ./ sin(x(mask));
end