Extracting non-zero values from a matrix and storing its row,column index and its associated value.

12 ビュー (過去 30 日間)
Could anyone help me build and correct my code which aims to only save the non-zero elements of an arbitrary square matrix and its index? Basically I need to write a script that does the same function as 'sparse' in MATLAB.
I want to have the same output as if I were to write sparse(A), where A is my matrix.
Here is my attempt:
`%Consider a 3x3 matrix
A=[ 0 0 9 ;-1 8 0;0 -5 0 ];
n=3; %size of matrix
%initialise following arrays:
RI= zeros(n,1); %row index
CI = zeros(n,1); %column index
V = zeros(n,1); %value in the matrix
for k = 1:n %row 1 to n
for j = 1:n %column 1 to n
if A(k,j)~=0
RI(k)=k;
CI(j)=j;
V(k,j)=A(k,j);
end
end
end`
  1 件のコメント
Chintan Patel
Chintan Patel 2020 年 3 月 6 日
Try this commad:
B = nonzeros(A)
This would extract all the non-zero elements of matrix A :)

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

採用された回答

Image Analyst
Image Analyst 2017 年 2 月 3 日
Try this
A = [0, 0, 9; -1, 8, 0; 0, -5, 0];
nonZeroIndices = A ~= 0;
% Extract those non-zero values into a new variable called output:
output = A(nonZeroIndices)
% Determine their row and column indices:
[rows, columns] = find(nonZeroIndices)
  2 件のコメント
Guillaume
Guillaume 2017 年 2 月 3 日
Even simpler:
[rows, colums, values] = find(A)
Image Analyst
Image Analyst 2017 年 2 月 3 日
OK, cool. I never even knew find() had a third output.

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

その他の回答 (0 件)

カテゴリ

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