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

1 回表示 (過去 30 日間)
Ömer Yaman
Ömer Yaman 2022 年 6 月 30 日
コメント済み: Ömer Yaman 2022 年 6 月 30 日
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

採用された回答

Chunru
Chunru 2022 年 6 月 30 日
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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

製品


リリース

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by