Error checking in a matrix
1 回表示 (過去 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
0 件のコメント
採用された回答
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 Center および File Exchange で Characters and Strings についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!