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일

3 개 추천

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일

0 개 추천

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

카테고리

도움말 센터File Exchange에서 MATLAB에 대해 자세히 알아보기

질문:

CM
2017년 3월 9일

답변:

2017년 3월 9일

Community Treasure Hunt

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

Start Hunting!

Translated by