How to find what the value of a variable is in a loop using another variable in the loop?

1 vue (au cours des 30 derniers jours)
Hi,
Just trying to figure out how to get a value of a changing value in a loop if I have another value that is also looping. For example, here I am trying to figure out what motor speed a certain torque will give me:
for i=1:2000
%Increase Current through loop
I(i)=-0.1+(i*0.1);
%Calculate RPM with increasing Current
Omega(i)=((Ebat-(I(i)*R))/Ke)/((2*pi)/60);
%Calculate Torque with increasing Current
Torque(i) = Kt * I(i);
%This is my current attempt at getting the motor speed at a certain value of
%torque, however the torque is never exactly equal to TorqueReq which is a %constant
if Torque(i) == TorqueReq
x=MotorSpeed(i)
end
So If I have a certain value for torque, how can I find the corresponding value for speed at that torque? Thanks for any help!

Réponse acceptée

Image Analyst
Image Analyst le 5 Nov 2013
You need to read the FAQ, http://matlab.wikia.com/wiki/FAQ#Why_is_0.3_-_0.2_-_0.1_.28or_similar.29_not_equal_to_zero.3F, about why you should not compare floating point numbers for exact matches.
I fixed your code to check within a tolerance, as according to the FAQ:
tolerance = 0.001; % or some small number
for k=1:2000
%Increase Current through loop
I(k)=-0.1+(k*0.1);
%Calculate RPM with increasing Current
Omega(k)=((Ebat-(I(k)*R))/Ke)/((2*pi)/60);
%Calculate Torque with increasing Current
Torque(k) = Kt * I(k);
%This is my current attempt at getting the motor speed.
% TorqueReq is a constant.
if abs(Torque(k)- TorqueReq) < tolerance
x=MotorSpeed(k)
break; % if you want to exit the loop.
end
end
I also changed your loop index from i (the imaginary number) to k.

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by