Make a loop from this code

조회 수: 1 (최근 30일)
John
John 2022년 7월 25일
답변: William Rose 2022년 9월 4일
Need help making this a loop instead of the code I have now
  댓글 수: 1
KSSV
KSSV 2022년 7월 26일
What for loop you want?

댓글을 달려면 로그인하십시오.

답변 (1개)

William Rose
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')
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.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by