How to plot function with cases?

4 ビュー (過去 30 日間)
AbuYusuf
AbuYusuf 2017 年 4 月 16 日
回答済み: Star Strider 2017 年 4 月 16 日
I have problem executing cases for second function, f2 takes value based on the value of x for each band. Only one case which is the third case is not executed despite the condition is met. Can anyone help me finding the problem? Also, is there any other good way to do it.
x= [0.3:0.01:0.6];
f1 = [0.3:0.01:0.6];
f2 = zeros(size(f1));
for i=1:size(f1,2)
if x(1,i) <= 0.338
f2(1,i) = 5*x(1,i) - 0.50;
z=1;
elseif 0.338 < x(1,i) <= 0.465
f2(1,i) = 4*x(1,i) - 0.50;
z=2;
% it seems this case is not executed despite the condition is met?!!
elseif 0.465 < x(1,i) <= 0.584
f2(1,i) = 3*x(1,i) - 0.30;
z=3;
elseif x(1,i) > 0.584
f2(1,i) = 2*x(1,i) - 0.15;
z=4;
end
end
figure (1); plot(x, f1, 'b', x, f2, 'r--');

採用された回答

Star Strider
Star Strider 2017 年 4 月 16 日
The easy way is to use a version of ‘logical indexing’, and combine all the statements into one assignment (or in my code here, an anonymous function):
The Code
x = [0.3:0.01:0.6];
f1 = [0.3:0.01:0.6];
f2 = zeros(size(f1));
f2 = @(x) (x <= 0.338).*(5*x - 0.50) + ((0.338 < x) & (x <= 0.465)).*(4*x - 0.50) + ((0.465 < x) & (x <= 0.584)).*(3*x - 0.30) + (x > 0.584).*(2*x - 0.15);
figure (1)
plot(x, f1, 'b', x, f2(x), 'r--')
grid

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLine Plots についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by