Extracting non-zero values from a matrix and storing its row,column index and its associated value.
13 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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 Commento
Chintan Patel
il 6 Mar 2020
Try this commad:
B = nonzeros(A)
This would extract all the non-zero elements of matrix A :)
Risposta accettata
Image Analyst
il 3 Feb 2017
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 Commenti
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Matrix Indexing in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!