Need Help, Error in for loop

조회 수: 6 (최근 30일)
CM
CM 2017년 3월 9일
답변: John BG 2017년 3월 9일
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

채택된 답변

Walter Roberson
Walter Roberson 2017년 3월 9일
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.

추가 답변 (1개)

John BG
John BG 2017년 3월 9일
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

카테고리

Help CenterFile Exchange에서 MATLAB에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by