Defining (not plotting) a Piecewise Function with If, Else Statements

1 view (last 30 days)
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

Accepted Answer

Guillaume
Guillaume on 8 Oct 2014
if 0 <= var < 1/3
is not valid syntax in matlab, you need to use logical operators:
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
Guillaume on 8 Oct 2014
Right, yes, it's valid syntax, but it's meaningless and certainly not what the author intended.
Guillaume
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

Sign in to comment.

More Answers (0)

Categories

Find more on Argument Definitions in Help Center and File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!