To find value of variable using iteration

조회 수: 20 (최근 30일)
Dhananjay Singh
Dhananjay Singh 2021년 8월 28일
댓글: Image Analyst 2021년 8월 28일
Hello,
At first I need to generate a random number that was done using rand command.
Then I have to use iteration such that it satisfies a certain relation. I used while loop but it is not stopping.
x = rand(1,1);
while 350-12.9-x-32.4498 ~= 0
x= x+ 0.0001
end
The problem is other values can also change drastically so it would take a long time to find values. Any other suggestions?

채택된 답변

Image Analyst
Image Analyst 2021년 8월 28일
Your condition never matches 0 exactly. Why not? See the FAQ:
Try it like this:
x = rand(1,1);
maxIterations = 10000000; % Failsafe to prevent infinite loop
loopCounter = 0; % Failsafe to prevent infinite loop
value = abs(350-12.9-x-32.4498);
while value >= 0.00009 && (loopCounter < maxIterations)
x = x + 0.0001;
value = abs(350-12.9-x-32.4498);
loopCounter = loopCounter + 1; % Failsafe to prevent infinite loop
% fprintf('After %d iterations, x = %f and value = %f.\n', loopCounter, x, value);
end
fprintf('After %d iterations, x = %f and value = %f.\n', loopCounter, x, value);
You might get:
After 3038399 iterations, x = 304.650168 and value = 0.000032.
  댓글 수: 2
Dhananjay Singh
Dhananjay Singh 2021년 8월 28일
does rand function only generate number less than 1?
Image Analyst
Image Analyst 2021년 8월 28일
Yes, only between 0 and 1. See the help if you need it in a range different from that
r = vMin + (vMax - vMin) * rand(1); % Get value between vMin and vMax

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Awais Saeed
Awais Saeed 2021년 8월 28일
편집: Awais Saeed 2021년 8월 28일
What is your goal exactly? Do you want to find the value for x where the result is zero? You can find the roots using solve
syms x
vpa(solve(350-12.9-x-32.4498 == 0,x))
ans = 
304.65019999999999669171302230097
  댓글 수: 1
Dhananjay Singh
Dhananjay Singh 2021년 8월 28일
x = .. some guess number
y = f(x);
z= f(y);
w=g(y);
a=z+x+w;
x is to be guessed first ,then using relations find y,z,w and a is a constant value such that the relation satisfies.
was thinking of iteration of doing this . Is there any other method?

댓글을 달려면 로그인하십시오.

카테고리

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