Replacing zeros with other values

A=[1 2 3 4;
4 5 0 0;
1 0 0 1;
0 1 1 1]
I want to replace zeros in the third column with last known values. The result should be
A=[1 2 3 4;
4 5 3 0;
1 0 3 1;
0 1 1 1]
What should be the code.

 Respuesta aceptada

KSSV
KSSV el 4 de Nov. de 2016
A3=A(:,3);
A3(A3==0)=3;
A(:,3)=A3;

6 comentarios

Mido
Mido el 4 de Nov. de 2016
Thanks for your answer but what if it is a long column with other zeros I want the code to detect the known number before each zero and then replaces the zero with this number.
Mido
Mido el 4 de Nov. de 2016
while any(A(:)==0)
ii1=A==0;
ii2=circshift(ii1,[-1 0]);
A(ii1)=A(ii2);
end
I found this code in this forum but it solves the problem for all columns andI want it for the third column only.
KSSV
KSSV el 4 de Nov. de 2016
Make A as A3 and run it. Replace the column in A.
Mido
Mido el 4 de Nov. de 2016
Brilliant! Thank you very much.
Mido
Mido el 4 de Nov. de 2016
I have one more question. If I have a matrix like this
A= [1 1;
1 2;
1 3;
1 4;
2 1;
2 2;
2 3;
2 4]
I want to extract rows from the matrix as follows: For each different number in the first column extract rows using increment of 2 in the second column. The result will be:
A= [1 2;
1 4;
2 2;
2 4]
KSSV
KSSV el 4 de Nov. de 2016
A(2:2:end,:)

Iniciar sesión para comentar.

Más respuestas (0)

Preguntada:

el 3 de Nov. de 2016

Comentada:

el 4 de Nov. de 2016

Community Treasure Hunt

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

Start Hunting!

Translated by