Make a loop from this code
조회 수: 1 (최근 30일)
이전 댓글 표시
Need help making this a loop instead of the code I have now
답변 (1개)
William Rose
2022년 9월 4일
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.
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!