I have a matrix like this :
1 5 7 3 1 0
1 8 1 0 0 0
2 4 6 2 0 0
2 9 10 2 0 0
0 0 0 0 0 0
I want to change it to ...
1 5 7 3 1
1 8 1
2 4 6 2
2 9 10 2
please help me
CodePudding user response:
If the output can be a cell array then something like this will do it.
% assume input is the first matrix
output = cell(size(input,1), 1);
for i = 1:length(output)
output{i} = input(i, input(i, :) ~= 0);
end
What this does is create a cell array with the same number of rows as the original, then loops through the original finding the non-zero entries and keeping them.
You can keep just the non-zero values without retaining any of the row information with something like this:
output = input(input ~= 0);
This uses linear indexing and will flatten the matrix into a vector.
CodePudding user response:
For variety, here's a method that doesn't use loops:
in = [1 5 7 3 1 0; 1 8 1 0 0 0; 2 4 6 2 0 0; 2 9 10 2 0 0; 0 0 0 0 0 0]; % example data
[~, inds, vals] = find(in.'); % column indices and values of nonzeros of transposed input
result = accumarray(inds, vals, [size(in,1) 1], @(x){x.'}); % group by index
To understand how it works you may want to read the documentation of the find
and accumarray
functions, as well as this answer to see why the transpose is needed.