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!