Solving nonlinear equation inside for loop

조회 수: 7 (최근 30일)
Kim Ibrahim
Kim Ibrahim 2021년 11월 23일
댓글: Kim Ibrahim 2021년 12월 2일
I want to solve for p in the following equation: a1*P^0.5+a2*p+a3*p^1.5=k
if I need to iterate K from 1 to 10000 this is the code:
a1=1.4*10^25;
a2=2.7*10^24;
a3=1.311*10^23;
k=linspace(1,10000,10000);
syms p
for i=1:10000
p(i)=solve((a1*p(i)^0.5)+(a2*p(i))+(a3*p(i)^1.5)==k(i))
end
however I get the following error: Index exceeds the number of array elements (1).
Thank you.
  댓글 수: 3
Dyuman Joshi
Dyuman Joshi 2021년 11월 24일
You are expecting 3 solutions for each p and k, right?
Kim Ibrahim
Kim Ibrahim 2021년 11월 30일
yes, this equation gives 3 solutions for p when I give k a value at each itertion. the question is i can`t make the dimentions right beause for the 10000 iteration eah give out 3 solutions. That`s the error I get
"Unable to perform assignment because the left and right sides have a different number of elements."

댓글을 달려면 로그인하십시오.

채택된 답변

Matt J
Matt J 2021년 11월 30일
편집: Matt J 2021년 12월 1일
Your equations are really polynomials in p^0.5. Therefore, you can do,
a1=1.4*10^25;
a2=2.7*10^24;
a3=1.311*10^23;
k=linspace(1,10000,10000);
p=cell(1,numel(k));
for i=1:10000
coeffs=[a3,a2,a1,-k(i)]; %polynomial coefficients
p{i}=sqrt(roots(coeffs));
end
  댓글 수: 1
Kim Ibrahim
Kim Ibrahim 2021년 12월 2일
Thank you so much, the cell array helped.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by