Delete zeros from an array using for loops

1 visualización (últimos 30 días)
Juan Pérez Álvarez
Juan Pérez Álvarez el 16 de Feb. de 2022
Comentada: Juan Pérez Álvarez el 18 de Feb. de 2022
Hi I need delete zero elements of an array.
Note: I know theres a lot of way to complete this task.
Example: A = [1,0,2,3,0,0];
B = B(B~=0);
or
B = nonzeros(A);
I'm tryng this:
% Know the number of zeros
LA = length(A); Cont = 0;
for i = 1: LA
if A(i) == 0
Cont = Cont + 1;
end
end
% Dimention of the array B
LB = LA-Cont; B = zeros(LB,1);
for j=1:LB for k=1:LA
if A(k) ~= 0
B(j) =[A(k)];
end
end
end
Using this code I get this:
B = [3,3,3];
Because this code not reset when find a number different of zero.
Any idea? (using for loops)

Respuesta aceptada

David Hill
David Hill el 16 de Feb. de 2022
A = [1,0,2,3,0,0];
B=[];
for k=1:length(A)
if A(k)~=0
B=[B,A(k)];
end
end

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Productos


Versión

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by