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 Center および File ExchangeLine Plots についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by