Indexing polynomials using 'for' loop

조회 수: 8 (최근 30일)
Blazo Arsoski
Blazo Arsoski 2015년 4월 25일
편집: Stephen23 2015년 4월 26일
I need help about an exercise that I've been given from my professor. Six polynomials are given:
  • p1 = [0 2 0 -2 6 -1]; % the first polynomial is p1(x)=2x^4-2x^2+6x-1
  • p2 = [1 3 0 -2 0 0]; % the second polynomial is p2(x)=x^5+3x^4-5x^2
  • p3 = [0 0 3 1 0 -10]; %...
  • p4 = [0 0 0 -4 16 -5]; %...
  • p5 = [1 -1 0 1 0 -1];
  • p6 = [3 -12 0 0 0 7];
Using 'polyval(p(i),2/3)' function I should create new vector 'A' that contains all the values of the polynomials from 'p1' to 'p6'(i=1:6) for x=2/3. Then find the minimum and maximum value of the vector. I want to know how can I loop through the polynomials to find their value and put that value in the new vector. Thank you in advance.

채택된 답변

Mohammad Abouali
Mohammad Abouali 2015년 4월 25일
편집: Mohammad Abouali 2015년 4월 25일
%%Solution 1: (not recommended)
p1 = [0 2 0 -2 6 -1];
p2 = [1 3 0 -2 0 0];
p3 = [0 0 3 1 0 -10];
p4 = [0 0 0 -4 16 -5];
p5 = [1 -1 0 1 0 -1];
p6 = [3 -12 0 0 0 7];
polyValue=zeros(6,1);
for i=1:6
polyValue(i)=eval(sprintf('polyval(p%d,2/3)',i));
end
fprintf('Solution 1:(not recommended)\nmin: %f, max: %f.\n',min(polyValue),max(polyValue));
%%Solution 2:
p = [0 2 0 -2 6 -1; ...
1 3 0 -2 0 0; ...
0 0 3 1 0 -10; ...
0 0 0 -4 16 -5; ...
1 -1 0 1 0 -1; ...
3 -12 0 0 0 7];
polyValue=zeros(6,1);
for i=1:6
polyValue(i)=polyval(p(i,:),2/3);
end
fprintf('Solution 2:\nmin: %f, max: %f.\n',min(polyValue),max(polyValue));
Once you run it you get this results:
Solution 1:(not recommended)
min: -8.666667, max: 5.024691.
Solution 2:
min: -8.666667, max: 5.024691.
As you can see the difference between the solutions is slightly how the polynomial coefficients are stored.
  댓글 수: 3
Mohammad Abouali
Mohammad Abouali 2015년 4월 25일
you are welcome
Stephen23
Stephen23 2015년 4월 26일
편집: Stephen23 2015년 4월 26일
@Blazo Arsoski: and please note the advice that solution one is "not recommended" dues to relying on eval. Read more to know why:

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

추가 답변 (0개)

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by