Replace numbers in a matrix depending on if statement
조회 수: 5 (최근 30일)
이전 댓글 표시
Dear all Community members,
I have a 5x5 matrix that contains only numerical values. I want to remove values below a given threshold and add the sum of these values to the next horisontal element that is above the threshold.
My input matrix is as follows:
A=[1 6 7 8 13; 1 3 11 8 15; 1 2 4 13 19; 1 3 4 8 11; 1 3 4 5 11];
Threshold value=5
I.e. I want to replace all values <=5 with zeros and add the sum of these to the next horisontal element that is above the threshold. So the output matrix shall be:
B=[0 7 7 8 13; 0 0 15 8 15; 0 0 0 20 19; 0 0 0 16 11; 0 0 0 0 24];
Can anyone assist me?
Thanks in advance.
댓글 수: 0
채택된 답변
KSSV
2020년 6월 10일
편집: KSSV
2020년 6월 10일
A(A<=5) = 0
댓글 수: 3
KSSV
2020년 6월 10일
A=[1 6 7 8 13; 1 3 11 8 15; 1 2 4 13 19; 1 3 4 8 11; 1 3 4 5 11];
B=[0 7 7 8 13; 0 0 15 8 15; 0 0 0 20 19; 0 0 0 16 11; 0 0 0 0 24];
val = 5 ;
C = A ;
for i = 1:size(A,1)
idx = A(i,:)<=val ;
id = find(idx) ;
C(i,idx) = 0 ;
thesum = sum(A(i,idx)) ;
C(i,id(end)+1) = thesum+C(i,id(end)+1) ;
end
C
추가 답변 (0개)
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!