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

1 次查看(过去 30 天)
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

采纳的回答

Guillaume
Guillaume 2014-10-8
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 个评论
Guillaume
Guillaume 2014-10-8
Right, yes, it's valid syntax, but it's meaningless and certainly not what the author intended.
Guillaume
Guillaume 2014-10-8
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

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Argument Definitions 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by