Problem when plotting a graph after for and if else if

1 view (last 30 days)
--------------------------
C = 100;
g = 20;
s = 0.5;
T = 1;
t = 0.68;
x = 0:0.1:1
if x <t
d = 32/(1.-x*0.2)
else d = C*(1-g/C)^2./(2*(1.-x*g/C))+900*T*((x-1.)+sqrt((x-1).^2+12*C*(x-t)./(T*s*g*3600)))
end
plot(x,d)
-----------------------
Anyone help me. I dont understant why d(x=0)=21.64.
while: d(x=0<0.68)=32*(1-0)=32
Please explain help me why?
Thanks so much!

Accepted Answer

Image Analyst
Image Analyst on 9 Jun 2020
Edited: Image Analyst on 9 Jun 2020
It's because of the way you set up your if statement. You're comparing the whole x to t so you're getting a logical vector and then you're basically saying if vector. You should either vectorize the indexes, or use a for look like this:
C = 100;
g = 20;
s = 0.5;
T = 1;
t = 0.68;
x = 0:0.1:1
for k = 1 : length(x)
if x(k) < t
d(k) = 32 ./ (1 - x(k) * 0.2);
fprintf('For k = %d, x(k) = %.1f, and d(k) = %.1f. x is less than t.\n', k, x(k), d(k));
else
d(k) = C*(1-g/C)^2./(2*(1.-x(k)*g/C))+900*T*((x(k)-1.)+sqrt((x(k)-1).^2+12*C*(x(k)-t)./(T*s*g*3600)));
fprintf('For k = %d, x(k) = %.1f, and d(k) = %.1f. x is greater than t.\n', k, x(k), d(k));
end
end
plot(x, d, 'b.-', 'MarkerSize', 20)
grid on;
d
Here is the vectorized version:
C = 100;
g = 20;
s = 0.5;
T = 1;
t = 0.68;
x = 0:0.1:1
% Initialize all elements to this equation.
d = C*(1-g/C)^2./(2*(1.-x*g/C))+900*T*((x-1.)+sqrt((x-1).^2+12*C*(x-t)./(T*s*g*3600)));
% Now handle case there x is less than t.
indexes = x < t
d(indexes) = 32 ./ (1 - x(indexes) * 0.2);
plot(x, d, 'b.-', 'MarkerSize', 20)
grid on;
d

More Answers (0)

Categories

Find more on Line Plots in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!