- loop so that you apply periodic to only one element of x at a time, such as arrayfun(@periodic, x); OR
- loop inside periodic() over the elements of what was passed in, using appropriate indexing to set appropriate elements of y; OR
- learn how to use logical indexing.
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?
0 件のコメント
採用された回答
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:
0 件のコメント
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Function Creation についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!