Plotting a piecewise function

2 次查看(过去 30 天)
I have a function m-file, goes like this:
function y=periodic(x);
if x<=1
y=0;
end
if x > 1 & x < 2
y=x-1;
end
if x>=2 & x < 3
y=3-x;
end
if x>=3
y=0;
end
At prompt, when I type
x=0:0.1:4;
plot(x,periodic(x))
MATLAB returns 'Output argument "y" (and maybe others) not assigned during call to..' and points out that 'if x<=1' is in error. What is the problem here?

采纳的回答

Walter Roberson
Walter Roberson 2021-6-25
x=0:0.1:4;
That is a vector.
plot(x,periodic(x))
You are passing the entire vector to the function.
if x<=1
y=0;
end
You are comparing the entire vector to 1, getting a vector of true and false values. You are then using if with that vector. In MATLAB, when you use if or while with a non-scalar object, then the test is considered true only if all of the values being checked are non-zero. So if all of the values in the vector are <= 1 then you would set y to be a scalar 0.
Likewise, your other if test all of the vector, and if all of the elements satisfy the condition, then y is set to a scalar value in the final case (though a vector value in the middle two cases.)
You need to take one of three approaches:
  1. loop so that you apply periodic to only one element of x at a time, such as arrayfun(@periodic, x); OR
  2. loop inside periodic() over the elements of what was passed in, using appropriate indexing to set appropriate elements of y; OR
  3. learn how to use logical indexing.

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Function Creation 的更多信息

标签

产品


版本

R2014a

Community Treasure Hunt

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

Start Hunting!

Translated by