Loop-can you suggest another way to write the following loop?

Hello,
I'm trying to create an m.file to evaluate the polynomial P5(x)=a0+a1x+a2x^2+a3*x^3+a4*x^4+a5*x^5, where a is a vector [-120 274 -225 85 -15 1]. The following code is working but I'm a beginner and always like to know how ppl with experience might write the code. Many thanks for your cooperation so far..
---------------------------------------------------------------------------------------------------------
%polyfive.m syms x a=[-120 274 -225 85 -15 1]; p5old=0
for m=1:length(a) n=m-1; p5new=p5old+a(m)*x^(n); p5old=p5new; m=m+1 ; end disp(p5new)

 Risposta accettata

I wouldn’t write a loop at all. I would use polyval:
a=[-120 274 -225 85 -15 1];
x = linspace(0, 6);
y = polyval(fliplr(a), x);
figure(1)
plot(x, y)
grid

4 Commenti

B’s Answer moved here ...
Thanks!
Can you have a look at the code that I've written? How can it be improved?
My pleasure!
I would not use the Symbolic Math Toolbox or a function file. I would use an anonymous function instead. I renumbered the ‘a’ coefficients to correspond to the MATLAB convention, and also vectorised it:
P5 = (a,x) a(6)+a(5).*x+a(4).*x.^2+a(3).*x.^3+a(2).*x.^4+a(1).*x.^5;
To read more about vectorisation, see the documentation on Vector vs. Matrix Operations.
Thanks a lot :)

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Loops and Conditional Statements in Centro assistenza e File Exchange

Tag

Community Treasure Hunt

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

Start Hunting!

Translated by