Extracting non-zero values from a matrix and storing its row,column index and its associated value.
12 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
JR
am 3 Feb. 2017
Kommentiert: Chintan Patel
am 6 Mär. 2020
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 Kommentar
Chintan Patel
am 6 Mär. 2020
Try this commad:
B = nonzeros(A)
This would extract all the non-zero elements of matrix A :)
Akzeptierte Antwort
Image Analyst
am 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 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!