loops
7 ビュー (過去 30 日間)
古いコメントを表示
ok i made my self a simpler code. what i am trying to accomplish is for MatLab to give me the M at which A and z are equal. Here is my code.
A=1.687;
gamma=1.4;
tol=1e4;
for M=1:1:5
a=(1/M^2);
b=(2/(gamma+1));
c=(1+(((gamma-1)/2)*M^2));
d=(gamma+1)/(gamma-1);
z(M)=sqrt(a*((b*c)^d));
end
z'
if abs(A-z)<tol
M=z(M)
end
i cannot seem to get it to work. i got z' and i know M=2 is pretty close to my A value. FOr M=2 my code returns 1.6875. the if statement prints M=25.00, but i want it to print 2 because thats the answer. Thank you
0 件のコメント
回答 (5 件)
Moes
2011 年 3 月 11 日
Try this code instead (no loops):
A=1.687;
gamma=1.4;
tol=1e4;
M = 1:5;
a=(1./M.^2);
b=(2/(gamma+1));
c=(1+(((gamma-1)/2).*M.^2));
d=(gamma+1)/(gamma-1);
z=sqrt(a.*((b.*c).^d));
diffrnc = abs(A*ones(size(z)) - z)
diffrnc(find(diffrnc < tol))
1 件のコメント
Moes
2011 年 3 月 11 日
If you just want the index and not the actua;l number replace "diffrnc(find(diffrnc < tol))" with "find(diffrnc < tol)".
Walter Roberson
2011 年 3 月 11 日
z is an array, so A-z is an array and so abs(A-z) is an array. That array is compared to tol, which gives a logical array in return. When you use a logical array in an "if" statement, the "if" is only true if all of the logical values are true.
Replace the "if" with something like,
Mpos = find(abs(A-z)<tol);
M = z(Mpos);
That is a pretty large tol you have. Do you perhaps mean 1e-4 ?
0 件のコメント
Matt Fig
2011 年 3 月 11 日
Is this what you are looking for?
A=1.687;
gamma=1.4;
tol=1e-4;
IDX = 0:.0001:2;
z = zeros(1,length(IDX)); % Pre-allocate!
cnt = 0;
for M=IDX
a = (1/M^2);
b = (2/(gamma+1));
c = (1+(((gamma-1)/2)*M^2));
d = (gamma+1)/(gamma-1);
cnt = cnt + 1;
z(cnt) = sqrt(a*((b*c)^d));
if abs(A-z(cnt))<tol
M % Turns out there is more than one!
z(cnt)
% break
end
end
.
.
.
Here is another method of finding these two locations:
g = gamma; % For convenience...
f = @(M) sqrt((1./M.^2).*(((2./(g+1)).*(1+(((g-1)./2).*M.^2))).^((g+1)/(g-1)))) - A;
rt1 = fzero(f,2)
rt2 = fzero(f,.5)
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!