Replace numbers in a matrix depending on if statement
9 views (last 30 days)
Show older comments
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 Comments
Accepted Answer
KSSV
on 10 Jun 2020
Edited: KSSV
on 10 Jun 2020
A(A<=5) = 0
3 Comments
KSSV
on 10 Jun 2020
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
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!