Make a loop from this code
Afficher commentaires plus anciens
Need help making this a loop instead of the code I have now
1 commentaire
KSSV
le 26 Juil 2022
What for loop you want?
Réponses (1)
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')
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.
Catégories
En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!