Clear Filters
Clear Filters

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 view (last 30 days)
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 Comment
Guillaume
Guillaume on 24 May 2016
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...

Sign in to comment.

Answers (3)

Walter Roberson
Walter Roberson on 24 May 2016
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 on 24 May 2016
Edited: Guillaume on 24 May 2016
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 on 24 May 2016
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 Comments

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!