Fitting 65k rows with 6 points takes too much time with for loop.

1 view (last 30 days)
Dear helpful matlab users,
Previously I've asked a quesition about plotting +60k lines, by the help of you time cost reduced for plotting. But this time my issue is about generating slopes/coefficients.
I have two matrices which one of them has 65536 rows and 6 colums and the other one has 1 row 6 columns.. Let's say those matrices are M_1(1,6) and M_2(65536,6)
I would like to fit all rows as given below code section.
coefficients=zeros (65563,2);
for i=1:65536
coefficients(i,:) = polyfit (M_1, M_2(i,:),1);
end
Is there a way that I can reduce the time requires to calculate that portion of code.
for loop slows down everything.
Best Regars,
Ömer

Accepted Answer

Chunru
Chunru on 30 Jun 2022
n = 65536;
M_1 = randn(1, 6);
M_2 = randn(n, 6);
tic
coefficients=zeros (n,2);
for i=1:n
coefficients(i,:) = polyfit (M_1, M_2(i,:),1);
end
toc
Elapsed time is 0.934269 seconds.
% coefficients
% Polyfit cab be done by solving th vandermonde matrix system
% doc polyfit [and check out the algo]
tic
a = M_1'.^flip([0 1]); % 1st order polynomial
c = (a \ M_2')';
toc
Elapsed time is 0.009172 seconds.
% To check if the results agree
max(abs(c(:) - coefficients(:)))
ans = 4.4409e-16

More Answers (0)

Products


Release

R2020a

Community Treasure Hunt

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

Start Hunting!