フィルターのクリア

How can i find out all indices of nonzero elements in a sets of matrices?

3 ビュー (過去 30 日間)
Jiahong Zou
Jiahong Zou 2023 年 6 月 2 日
コメント済み: Jiahong Zou 2023 年 6 月 2 日
I have 19 sparse matrices which are 30000 * 30000 big. Each matrix is slightly different from another. How can i use [row, col] = find() function to get row and col vectors, which contain all position of nonzero element?
For example, A = [1 0; 0 0], B = [ 0 1; 0 0], C = [ 0 0 ; 1 0], D = [ 0 1; 1 0]
row = [ 1 1 2], col = [1 2 1]

採用された回答

Aman
Aman 2023 年 6 月 2 日
Hi Jiahong,
Assuming that you want to have unique pairs of row and column, the following code should work:
% Create a cell array of example sparse matrices
A = sparse([1 0; 0 0]);
B = sparse([0 1; 0 0]);
C = sparse([0 0; 1 0]);
D = sparse([0 1; 1 0]);
matrices = {A, B, C, D};
% Initialize empty row and column vectors
row = [];
col = [];
% Loop over each matrix in the cell array
for i = 1:numel(matrices)
% Use find to get the row and column indices of all nonzero elements
[r, c, ~] = find(matrices{i});
% Append the row and column indices to the overall row and column vectors
row = [row; r];
col = [col; c];
end
% Remove duplicate pairs from row and col
[row_col, idx] = unique([row, col], 'rows');
row = row_col(:,1);
col = row_col(:,2);
% Display the row and column vectors
row
col
If you want all pairs of row and column, use the following code:
% Create a cell array of example sparse matrices
A = sparse([1 0; 0 0]);
B = sparse([0 1; 0 0]);
C = sparse([0 0; 1 0]);
D = sparse([0 1; 1 0]);
matrices = {A, B, C, D};
% Initialize empty row and column vectors
row = [];
col = [];
% Loop over each matrix in the cell array
for i = 1:numel(matrices)
% Use find to get the row and column indices of all nonzero elements
[r, c, ~] = find(matrices{i});
% Append the row and column indices to the overall row and column vectors
row = [row; r];
col = [col; c];
end
% Display the row and column vectors
row
col
Hope this helps!
  1 件のコメント
Jiahong Zou
Jiahong Zou 2023 年 6 月 2 日
Hi Aman, thx for the answer. There are actually about 180000 nonzero elements in each matrix. I'm afraid it will run out of memory before removing duplicate pairs. Is there a more memory-saving way?

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

その他の回答 (1 件)

Jiahong Zou
Jiahong Zou 2023 年 6 月 2 日
Well this would work but is there a way not to repeat 19 times for 19 matrices?
[row, col] = find(A ~= 0 | B ~= 0 | C ~= 0 | D ~= 0)

カテゴリ

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

製品


リリース

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by