Error checking in a matrix

1 visualización (últimos 30 días)
Carsten
Carsten el 4 de Dic. de 2014
Comentada: Carsten el 4 de Dic. de 2014
I have the following code:
[r , c] = size(m);
if any(m(end,:)==-1)
m(m<0) = 0;
else
for a=r-1:-1:1
for b=1:c
if m(a,b)==-1
m(a,b)=m(a+1,b);
end
end
end
end
The code is checking if a matrix contains -1 in the last row. I have a couple of question regarding this code.It Works fine when checking from the last row to check for -1. If the is a -1 it replaces them all with zeros. If there are no -1 in the last row it locates the -1 and replace them with the value from the row that comes before. How do i do the opposite ? Check if the first row contains -1, and if so replace them with zeros. And if not then takes the value from the NeXT line and replace the -1 with that ?
Thanks a lot

Respuesta aceptada

Geoff Hayes
Geoff Hayes el 4 de Dic. de 2014
Carsten - just do something similar to what you have already, but opposite.
[r, c] = size(m);
if ~isempty(find(m(1,:)==-1))
m(m==-1) = 0;
else
for a=2:1:r
% get all indices of row a that correspond to elements
% of negative one
idcs = find(m(a,:)==-1);
if ~isempty(idcs)
m(a,idcs) = m(a-1,idcs);
end
end
end
Note how find is used to return the indices of the elements in the row that are negative one.
Try the above and see what happens!
  1 comentario
Carsten
Carsten el 4 de Dic. de 2014
Thank you so much for your help.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Characters and Strings en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by