Error checking in a matrix

3 次查看(过去 30 天)
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

采纳的回答

Geoff Hayes
Geoff Hayes 2014-12-4
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!

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by