How to plot function with cases?

4 次查看(过去 30 天)
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