Make a loop from this code
Show older comments
Need help making this a loop instead of the code I have now
1 Comment
KSSV
on 26 Jul 2022
What for loop you want?
Answers (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.
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!