Problem when plotting a graph after for and if else if

조회 수: 1 (최근 30일)
Le Duc Long
Le Duc Long 2020년 6월 9일
댓글: Le Duc Long 2020년 6월 9일
--------------------------
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!

채택된 답변

Image Analyst
Image Analyst 2020년 6월 9일
편집: Image Analyst 2020년 6월 9일
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

추가 답변 (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