I want to use polyfit in a NxM matrix rather than a for loop

11 views (last 30 days)
How can I do this in one line of code? For Loops Take too long.
for i=1:2^(9)
polydata_Run1 = polyfit((1:2^(11))',SEG_RUN1(:,i),1);
Best_Fit_(:,i) = polyval(polydata_Run1,(1:2^(11)));
end

Accepted Answer

Matt J
Matt J on 8 Nov 2013
Edited: Matt J on 8 Nov 2013
A=[linspace(0,1,2^11);ones(1,2^11)].';
[Q,R]=qr(A,0);
Best_Fit_ = A*(R\(Q'*SEG_RUN1));
  2 Comments
Richard Liggiero
Richard Liggiero on 8 Nov 2013
That is it! Would have never figured that one out, you are a math legend
Matt J
Matt J on 8 Nov 2013
Edited: Matt J on 8 Nov 2013
Come to think of it, you can probably simplify to
A=[linspace(0,1,2^11);ones(1,2^11)].';
Best_Fit_ = A*(A\SEG_RUN1);
I've set A up to be pretty well-conditioned, so QR-deomposition shouldn't be necessary.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!