Need Help, Error in for loop
7 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
CM
am 9 Mär. 2017
Beantwortet: John BG
am 9 Mär. 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
0 Kommentare
Akzeptierte Antwort
Walter Roberson
am 9 Mär. 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.
0 Kommentare
Weitere Antworten (1)
John BG
am 9 Mär. 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
0 Kommentare
Siehe auch
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!