Error checking in a matrix

1 Ansicht (letzte 30 Tage)
Carsten
Carsten am 4 Dez. 2014
Kommentiert: Carsten am 4 Dez. 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

Akzeptierte Antwort

Geoff Hayes
Geoff Hayes am 4 Dez. 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 Kommentar
Carsten
Carsten am 4 Dez. 2014
Thank you so much for your help.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Characters and Strings finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by