Extract non zero elements from 2D array

Hi I have an array like this:
I want to extract non-zero elements for each row, e.g for second row, it should be 3,4. (and other array elements are zero) for third row 1,3,4 I think 3d array will be used and i tried this code, but incorrect results.
for m=1:r
for k=1:row
for l=1:col
if(a(k,l)~=0)
b(k,l,m)=a(k,l);
end
end
end
end
(a for array given above and b is new array with results) Any help will be highly appreciated.

 Respuesta aceptada

Stephen23
Stephen23 el 2 de Abr. de 2017
No ugly loops are required:
>> [R,C] = find(X)
>> out = accumarray(R,X(X~=0),[],@(n){n});
>> out{2} % second row
ans =
4
3
>> out{3} % third row
ans =
3
1
4

4 comentarios

Tha saliem
Tha saliem el 2 de Abr. de 2017
Thanks alot. Can I do this without using cell array?
@Tha saliem: how do you want unequally sized vectors joined together? In one long column is easy:
>> Y = X.';
>> Y(Y~=0)
ans =
3
4
1
3
4
2
1
2
3
4
5
However if you want them arranged in some other way then you have to describe exactly how, because there are a million ways that fit your requirement of "without using cell array", but you did not give any description of what you actually want. It is hard to develop code when you do not give a specification of what you actually want.
Tha saliem
Tha saliem el 2 de Abr. de 2017
Can I do it using 3D array instead of cell array?
Stephen23
Stephen23 el 2 de Abr. de 2017
@Tha saliem: sure, anything is possible, but you need to tell us what you want to do with the unequally-sized vectors. Do you want to pad them to the same size, or what?
For example, exactly how do you want [3;4] and [1;3;4] arranged in this 3D array, considering that they have different lengths?

Iniciar sesión para comentar.

Más respuestas (1)

Nicolaie Popescu-Bodorin
Nicolaie Popescu-Bodorin el 2 de Abr. de 2017
Editada: Stephen23 el 2 de Abr. de 2017
% Let A be a 2D Array and NZI the cell containing indices of non-zero elements on each column.
% preallocation:
sa = size(A,2); NZI{sa}=[];
for k=1:sa,
NZI{k} = find(A(:,k)~=0);
end
Kind regards, Nicolaie Popescu-Bodorin, www.lmrec.org/bodorin/

Categorías

Más información sobre Creating and Concatenating Matrices en Centro de ayuda y File Exchange.

Etiquetas

Preguntada:

el 2 de Abr. de 2017

Comentada:

el 2 de Abr. de 2017

Community Treasure Hunt

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

Start Hunting!

Translated by