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

12 views (last 30 days)
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`

Accepted Answer

Image Analyst
Image Analyst on 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)

More Answers (0)

Community Treasure Hunt

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

Start Hunting!