Defining (not plotting) a Piecewise Function with If, Else Statements
1 view (last 30 days)
Show older comments
I have the following, which doesn't work. Does anyone have any recommendations? I need a simple piecewise constant function.
function [ x ] = m0( var1 )
if 0 <= var1 < 1/3 x = 1/sqrt(2); else if 1/3 <= var1 < 2/3 x = 0; else x = -1/sqrt(2); end end end
0 Comments
Accepted Answer
Guillaume
on 8 Oct 2014
if 0 <= var < 1/3
if var1 >= 0 && var1 < 1/3
x = 1/sqrt(2);
elseif var1 >= 1/3 && var1 < 2/3
x = 0;
else
x = -1/sqrt(2);
end
6 Comments
Guillaume
on 8 Oct 2014
Right, yes, it's valid syntax, but it's meaningless and certainly not what the author intended.
Guillaume
on 8 Oct 2014
Steven,
Yes, sorry, your function is only meant to work with scalars, and you're passing an array. This function would work:
y = function m0(x)
y = zeros(size(x));
y(x >= 0 & x < 1/3) = 1/sqrt(2);
y(x >= 2/3) = -1/sqrt(2);
end
More Answers (0)
See Also
Categories
Find more on Argument Definitions in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!