could anyone help me how to check the idx position containing value is not equal to zero
조회 수: 8 (최근 30일)
이전 댓글 표시
my code generates idx =[2 5 7 12 15]
Before i want to proceed i need to check whether the above mentioned position contain zero or non zero values.
If it contains non zero values i can proceed or else i need to change the idx position till i get all the position containing non zero values.
Could anyone please help me on it.
댓글 수: 0
답변 (2개)
Steven Lord
2019년 6월 5일
a(idx) will give you the elements in a whose linear indices are stored in idx. You can check if they are exactly equal to 0 using the == operator.
a = [1 2 0 3 4; 0 5 6 7 0; 8 0 9 0 10];
idx = [2 6 8 12 15];
zeroLocations = a(idx) == 0;
indicesCorrespondingToZero = idx(zeroLocations)
If you need to modify idx, use zeroLocations to index into idx on assignment. Here I'm going to overwrite them with NaN but you could do computations on them, remove them, etc.
idx(zeroLocations) = NaN
댓글 수: 7
Rik
2019년 6월 6일
Since you don't care which element is chosen, you can use the second output of the max function.
a = [1 2 0 3 4; 0 5 6 7 0; 8 0 9 0 10];
%if a might contain negative values, use this instead:
%[val,row_idx]=max(abs(a),[],1);
[val,row_idx]=max(a,[],1);
if any(~nnz(val))
error('some cols have only zeros')
end
idx=sub2ind(size(a),row_idx,1:size(a,2));
참고 항목
카테고리
Help Center 및 File Exchange에서 Resizing and Reshaping Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!