loops
7 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Réponses (5)
Moes
le 11 Mar 2011
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 commentaire
Moes
le 11 Mar 2011
If you just want the index and not the actua;l number replace "diffrnc(find(diffrnc < tol))" with "find(diffrnc < tol)".
Walter Roberson
le 11 Mar 2011
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 commentaires
Matt Fig
le 11 Mar 2011
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 commentaires
Voir également
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!