Replace for loop with matrix function, for function acting on matrix columns
古いコメントを表示
Let L be an n x n matrix, and let M be an n x p matrix. (In practice p << n/2, but n is of order 10^{5} or greater). I'd like to construct the n x p matrix N, with entries $N_{ij} = sum_k L_{ki}/M_{kj}$.
At present I'm using the for loop below. How can it be accelerated/avoided?
% Generate random matrices %
n = 100; p = 35;
L = rand(n,n);
M = rand(n,p);
%
% Produce N from L and M, where N_{ij} = sum_k Lki/Mkj %
N = inf(n,p);
for i = 1:n
Li = L(:,i);
for j = 1:p
Mj = M(:,j);
N(i,j) = sum(Li./Mj);
end
end
採用された回答
その他の回答 (2 件)
Bruno Luong
2018 年 10 月 24 日
N = L.' * (1./M)
5 件のコメント
Stephen23
2018 年 10 月 24 日
+1 best use of MATLAB
greengunpowder
2018 年 10 月 24 日
Bruno Luong
2018 年 10 月 24 日
編集済み: Bruno Luong
2018 年 10 月 24 日
But do you know which method is more accurate?
greengunpowder
2018 年 10 月 24 日
Bruno Luong
2018 年 10 月 24 日
The order of the summation is different when one uses SUM, or MTIMES and it also depends on the number of threads (so the CPU that MATLAB is running), which in return gives different summation results. So far the discrepancy is observed, but AFAIK no-one is able to question matrix MTIMES in a causual use cases.
madhan ravi
2018 年 10 月 24 日
編集済み: madhan ravi
2018 年 10 月 24 日
n = 100;
p = 35;
M = rand(n,p)
L = rand(n,n)
N = sum(L./M)
2 件のコメント
madhan ravi
2018 年 10 月 24 日
You don't need loop to do this operation
greengunpowder
2018 年 10 月 24 日
カテゴリ
ヘルプ センター および File Exchange で Numerical Integration and Differentiation についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!