MATLAB: Elementwise If statement, then apply an equation/function only to the elements that meet the criteria

elementwise array function if elseif

Pretty self explanitory, but couldn't find an answer after much searching. i hope there's a simple solution to this:
say I have a matrix:
x = rand(3,3)
and I want to find all values in the matrix that are greater than zero and apply some elementwise equation, and for all values that are less than zero, apply a different elementwise function. like this:
if x>0
y = x.^2
elseif x<0
y = x.^3
end
is there a way to do this?

Best Answer

For this specific example:
x = magic(3)-5;
idx = sign(x);
x(idx==1) = x(idx==1).^2;
x(idx==-1) = x(idx==-1).^3;
In general you can use logical indexing to turn any type of logical expression into an index.
Related Question