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 CenterFile Exchange에서 Line Plots에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by