Removing zeros from matrix
70 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Robert Bridges
el 7 de Dic. de 2021
Hi,
Been trying to remove these zeros using NaN and find etc. but to no avail.
Trying to remove zeros so that I can pull out the end (non-zero) values from each row and put into a new n:1 matrix. If there is also a way of doing this without nessisarily having to remove the zeros then that would be fine also.
Example matrix (mine is a lot larger but follows similar format with zeros being at the end of the rows):
A = [1 2 3 4 5 6; 1 2 3 4 5 6; 1 2 3 4 5 0; 1 2 3 4 0 0; 1 2 3 0 0 0]
Thanks in advance.
Edit:
The final desired output would be:
B = [6; 6; 5; 4; 3]
0 comentarios
Respuesta aceptada
Stephen23
el 7 de Dic. de 2021
Editada: Stephen23
el 7 de Dic. de 2021
A = [1,2,3,4,5,6;1,2,3,4,5,6;1,2,3,4,5,0;1,2,3,4,0,0;1,2,3,0,0,0]
Method one: NONZEROS and CELLFUN
baz = @(v)v(end);
fnh = @(v)baz(nonzeros(v));
B = cellfun(fnh,num2cell(A,2))
Method two: ROT90 and CUMSUM and logical indexing
tmp = rot90(A);
idx = tmp~=0;
idx = idx & cumsum(idx,1)==1;
B = tmp(idx)
Method 3: FIND and CELLFUN
foo = @(v)v(find(v,1,'last'));
B = cellfun(foo,num2cell(A,2))
Method 4: MAX and SUB2IND and linear indexing:
sza = size(A);
idc = max((A~=0).*(1:sza(2)),[],2);
idr = 1:sza(1);
B = A(sub2ind(sza,idr(:),idc))
0 comentarios
Más respuestas (2)
Alan Stevens
el 7 de Dic. de 2021
Like this?
A = [1 2 3 4 5 6; 1 2 3 4 5 6; 1 2 3 4 5 0; 1 2 3 4 0 0; 1 2 3 0 0 0];
B = A'; B=B(:);
B(B==0)=[]
3 comentarios
Stephen23
el 7 de Dic. de 2021
Every row must have the same number of elements, so this is not a valid matrix:
B = [1 2 3 4 5 6; 1 2 3 4 5 6; 1 2 3 4 5; 1 2 3 4; 1 2 3]
Would you like to replace the zeros with NaNs instead?
Jan
el 7 de Dic. de 2021
What is the wanted output?
A = [1 2 3 4 5 6; 1 2 3 4 5 6; 1 2 3 4 5 0; 1 2 3 4 0 0; 1 2 3 0 0 0];
B1 = A;
B1(B1 == 0) = NaN
B2 = A(A~=0)
I'm not sure what this means: "pull out the end (non-zero) values from each row and put into a new n:1 matrix"
Maybe:
B = cell(height(A), 1);
for k = 1:height(A)
B{k} = A(k, A(k, :) ~= 0);
end
1 comentario
Ver también
Categorías
Más información sobre Logical en Help Center y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!