How to plot function with cases?

4 Ansichten (letzte 30 Tage)
AbuYusuf
AbuYusuf am 16 Apr. 2017
Beantwortet: Star Strider am 16 Apr. 2017
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--');

Akzeptierte Antwort

Star Strider
Star Strider am 16 Apr. 2017
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

Weitere Antworten (0)

Kategorien

Mehr zu Line Plots finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by