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
0 个评论
采纳的回答
Guillaume
2014-10-8
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 个评论
Guillaume
2014-10-8
Right, yes, it's valid syntax, but it's meaningless and certainly not what the author intended.
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 Center 和 File Exchange 中查找有关 Argument Definitions 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!