フィルターのクリア

Summing of non-zero elements of columns using indexing

4 ビュー (過去 30 日間)
D_coder
D_coder 2018 年 9 月 16 日
コメント済み: D_coder 2018 年 9 月 16 日
I have idx, is there a way of using idx to make the sum(matrix,1) in the below code cheaper. In another words, is it possible to use idx for calculating sum of 'matrix'(see below code) along the columns to get a row vector.
matrix(matrix<thresh) = 0 ;
idx = find(matrix~=0);
while condition is true
matrix(idx) = matrix(idx).*another matrix(idx) %matrix is sparse and has lot of zeros ;numel(matrix) = 1000000
new_matrix(a,:) = b*sum(matrix,1) %here b is an integer, make this line efficient and faster so it takes only non zero elements for summing
end

回答 (2 件)

Walter Roberson
Walter Roberson 2018 年 9 月 16 日
Yes, it is possible to use idx to reduce the number of additions.
matrix(matrix<thresh) = 0 ;
idx = find(matrix~=0);
[idxr, idxc] = ind2sub(size(matrix), idx);
numcol = size(matrix,2);
while condition is true
matrix(idx) = matrix(idx).*another matrix(idx) %matrix is sparse and has lot of zeros ;numel(matrix) = 1000000
for col = 1 : num2col
matched_rows = idxr(idxc==col);
new_matrix(a,col) = b * sum(matrix(matched_rows, col));
end
end
I would be surprised if this is more efficient, but it is possible . It would probably be more efficient to loop calculating the column-wise indices into a cell array and indexing into that.
  1 件のコメント
D_coder
D_coder 2018 年 9 月 16 日
編集済み: D_coder 2018 年 9 月 16 日
do you have any alternative code without use of for loop coz the while loop runs 9000 times so thats gonna consume a lot of time.accumarray()?

サインインしてコメントする。


Akira Agata
Akira Agata 2018 年 9 月 16 日
If your matrix contains many zeros, I would recommend converting it to sparse matrix and applying sum function, like the following. It runs faster.
matrix = sparse(matrix); % Convert to sparse matrix
summedValue = sum(matrix,1);
  3 件のコメント
Walter Roberson
Walter Roberson 2018 年 9 月 16 日
But you would convert to sparse outside the loop.
D_coder
D_coder 2018 年 9 月 16 日
No then my element by element multiplication would suffer

サインインしてコメントする。

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by