Iterations until condition is met

조회 수: 4 (최근 30일)
aregr8
aregr8 2023년 4월 7일
댓글: aregr8 2023년 4월 7일
clear all; clc
ER = 50;
gamma = 1.4;
for M=1:0.01:10
if (1/M) * ((2/(gamma+1))*(1+((gamma-1)/2)*(M^2)))^((gamma+1)/(2*gamma-2)) == ER
mach = M
break
end
end
I am trying to iterate M from 1 to 10 in intervals of 0.01 until the equation value matches my value for ER. Can you please help me figure out where I went wrong?

채택된 답변

Torsten
Torsten 2023년 4월 7일
ER = 50;
gamma = 1.4;
M = 1:0.00001:10;
expr = (1./M) .* ((2/(gamma+1))*(1+((gamma-1)/2)*(M.^2))).^((gamma+1)./(2*gamma-2)) - ER;
[error,index] = min(abs(expr))
error = 1.6950e-04
index = 491378
Mstar = M(index)
Mstar = 5.9138
  댓글 수: 1
aregr8
aregr8 2023년 4월 7일
Thank you very much for your help.

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

추가 답변 (1개)

the cyclist
the cyclist 2023년 4월 7일
Instead of checking
if (1/M) * ((2/(gamma+1))*(1+((gamma-1)/2)*(M^2)))^((gamma+1)/(2*gamma-2)) == ER
you could do something like
tol = 1.e-6; % Choose a suitable tolerance here
if abs(((1/M) * ((2/(gamma+1))*(1+((gamma-1)/2)*(M^2)))^((gamma+1)/(2*gamma-2))) - ER) < tol
Probably even better would be to use a while loop instead of a for loop, which is the more natural construct for looping until a condition no longer holds. (But you may still need to be careful about floating point precision.)
  댓글 수: 1
aregr8
aregr8 2023년 4월 7일
Thank you very much for your help.

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

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품


릴리스

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by