Need Help, Error in for loop

7 vues (au cours des 30 derniers jours)
CM
CM le 9 Mar 2017
I have to find the root of an equation, but I get an error saying 'Error using * , and also an error in line 12 but.
T=1.2;
P=(0:2:10);
A=0.45724.*(P/T.^2).*(1+0.392.*(1-T.^0.5)).^2;
B=0.0778.*(P/T);
f=@(Z) Z.^3-(1-B).*Z.^2+(A-B.*2-3.*B.^2).*Z-(A.*B-B.^2-B.^3);
xl=0;
xu=6;
xm=0;
maxiter=15;
for i=1:maxiter;
xold=xm;
if f(xm)*f(xu)<0; %<-- Line 12
xl=xm;
else
xu=xm;
end
xm=(xu+xl)/2;
ea=abs((xm-xold)/xm);
xold=xm;
end

Réponse acceptée

Walter Roberson
Walter Roberson le 9 Mar 2017
You have
P=(0:2:10);
so P is a vector.
B=0.0778.*(P/T);
B involves P, so B is a vector.
f=@(Z) Z.^3-(1-B).*Z.^2+(A-B.*2-3.*B.^2).*Z-(A.*B-B.^2-B.^3);
f(Z) involves B, so f(Z) is a vector.
Your code is expecting f(Z) to be a scalar.

Plus de réponses (1)

John BG
John BG le 9 Mar 2017
Hi CM
got your code to work, but not sure the result is what you expect, please confirm
T=1.2;
maxiter=15;
P=[0:2:10];
% P=linspace(0,10,maxiter)
A=0.45724.*(P/T).^2.*(1+0.392.*(1-T.^0.5)).^2;
B=0.0778.*(P/T);
f=@(Z,A,B) Z^3-(1-B)*Z^2+(A-B*2-3*B^2)*Z-(A*B-B^2-B^3);
% Y=Z^3-(1-B)*Z^2+(A-B*2-3*B^2)*Z-(A*B-B^2-B^3);
xl=0;
xu=6;
xm=0;
for i=1:maxiter;
xold=xm;
if f(xm,A,B)*f(xu,A,B)<0; %<-- Line 12
xl=xm;
else
xu=xm;
end
xm=(xu+xl)/2;
ea=abs((xm-xold)/xm);
xold=xm;
end
I have added as comment the lines
P=linspace(0,10,maxiter)
Y=Z^3-(1-B)*Z^2+(A-B*2-3*B^2)*Z-(A*B-B^2-B^3);
because there may be a way to simplify, remove at least the for loop.
if you find this answer useful would you please be so kind to mark my answer as Accepted Answer?
To any other reader, please if you find this answer of any help,
please click on the thumbs-up vote link,
thanks in advance
John BG

Catégories

En savoir plus sur MATLAB 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