Plotting a piecewise function

2 ビュー (過去 30 日間)
Ali Kiral
Ali Kiral 2021 年 6 月 25 日
回答済み: Walter Roberson 2021 年 6 月 25 日
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 Center および File ExchangeFunction Creation についてさらに検索

タグ

製品


リリース

R2014a

Community Treasure Hunt

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

Start Hunting!

Translated by