I want to print the value of t when value of vc1 is 90.5931 but I am not able to do so. please help

1 次查看(过去 30 天)
for t1=0:0.00001:0.15
vc1 = 100-100*exp(-5000*t1)*(cosh(2000*6^(1/2)*t1) + ...
(5*6^(1/2)*sinh(2000*6^(1/2)*t1))/12);
while(vc1 == 90.5931)
display(t1)
end
plot(t1,vc1)
hold on
end
  1 个评论
Guillaume
Guillaume 2016-5-24
Note that you're actually lucky that your comparison didn't work as if it did, you would have entered a never ending loop
while vc1 == 90.5931
display(t1)
end
means: enter the loop if vc1 is equal to 90.5931, then display t1 and try the loop again. Since vc1 has not change, it will display t1 again and try again, and again...

请先登录,再进行评论。

回答(3 个)

Walter Roberson
Walter Roberson 2016-5-24
t1 =0:0.00001:0.15;
vc1 = 100 - 100*exp(-5000*t1) .* (cosh(2000*6^(1/2)*t1) + ...
(5*6^(1/2)*sinh(2000*6^(1/2)*t1))/12);
plot(t1, vc1);
tidx = find(vc1 >= 90.5931, 1, 'first');
t1(tidx)

Guillaume
Guillaume 2016-5-24
编辑:Guillaume 2016-5-24
As per Dr Siva's answer, do not use == to compare floating points numbers unless the two numbers have been obtained exactly the same way (both results of the same calculation or both typed in the code), due to floating point accuracy (the way numbers are actually stored and the round-off error of calculation).
Always compare the absolute difference of the number relative to an arbitrary small number. Some multiple of eps may be a good idea (the actual function not some made up variable with an unrealistic value), or just an arbitray small number. In your case, the actual value is around 2*1e-5 away from 90.5931, so I suggest using 1e-4
if abs(vc1 - 90.5931) < 1e-4 %with no eps variable existing
To answer your second problem, the slow plotting, the answer is not to use a loop:
t1 = 0 : 1e-5 : 0.15;
vc1 = 100 - 100*exp(-5000*t1) .* (cosh(2000*6^(1/2)*t1) + ...
(5*6^(1/2)*sinh(2000*6^(1/2)*t1))/12);
plot(t1, vc1, '.r');
%and to find for which t1, vc1 is near 90.5953:
t90 = t1(abs(vc1 - 90.5931) < 1e-4)

KSSV
KSSV 2016-5-24
Dont try to equate floating point numbers. Try the following:
eps = 10^-100 ; % Set a small number epsilon for equating
for t1 =0:0.00001:0.15
vc1 = 100-100*exp(-5000*t1)*(cosh(2000*6^(1/2)*t1) + ...
(5*6^(1/2)*sinh(2000*6^(1/2)*t1))/12);
if ((vc1 - 90.5931)< eps)
display(t1)
end
plot(t1,vc1,'.r')
drawnow
hold on
end
  4 个评论

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by