Make a loop from this code

3 visualizzazioni (ultimi 30 giorni)
John
John il 25 Lug 2022
Risposto: William Rose il 4 Set 2022
Need help making this a loop instead of the code I have now

Risposte (1)

William Rose
William Rose il 4 Set 2022
Perhaps you want to do a speed test comparing the vectorized code inyour function to a for-loop equivalent.
Your code finds the coefficients of a cubic polynomial fit to the data in vectors x,y.
Therefore I create a y vector that is a cubic function of x, plus noise. Then I write a neested set of for loops to take the place of the commented-out line.
x=-5:5;
ce=[-10,1,-1,2]; %cubic equation coefficients
%y=ce0 + ce1*x + ce2*x^2 + ce3*x^3
y=ce(1)*ones(size(x))+ce(2)*x+ce(3)*x.^2+ce(4)*x.^3+randn(1,length(x));
%Next: write code that uses for loops, in place of John's function
k=3;
%X=[x(:).^(0:k)]; %X will be length(x)-by-4
X=zeros(length(x),4);
for i=1:length(x)
for j=0:k
X(i,j+1)=x(i)^j;
end
end
y=y(:);
c=X\y;
p=fliplr(c')
p = 1×4
2.0068 -1.0714 0.8639 -9.2910
Note that p is in the opposite order of ce, due to the flip operation. You could also write for loops to accomplish the operation c=X/y. That will be more complicated.
Good luck.

Categorie

Scopri di più su Loops and Conditional Statements in Help Center 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