Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MATLAB return of vector function with IF statement

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
like image 899
bergmeister Avatar asked May 03 '26 05:05

bergmeister


1 Answers

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))
like image 132
Jonas Avatar answered May 04 '26 19:05

Jonas