MATLAB: Replace numbers in a matrix depending on if statements from arrays

arrayfor loopif statementMATLABmatrixmatrix arraymatrix manipulation

Dear all Community members,
I have a 5×5 matrix and two arrays (1×5 and 5×1) that contains only numerical values. I want to remove values below a variable threshold matrix and add the sum of these values to the next horisontal element (row wise) 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];
h=[0.5;1;2;2.5;3];
t=[1 2 3 4 5];
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];
for i = 1:size(h)
for j = 1:size(t)
thres(i,j)=3.1*sqrt(h(i))
end
end
Resulting threshold matrix will be:
thresh=[2.2 2.2 2.2 2.2 2.2; 3.1 3.1 3.1 3.1 3.1; 4.4 4.4 4.4 4.4 4.4; 4.9 4.9 4.9 4.9 4.9; 5.4 5.4 5.4 5.4 5.4];
I.e. I want to replace all values <=thresh 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.

Best Answer

thresh = 3.1 * sqrt(h);
ix = A <= thresh;
s = sum(A .* ix,2);
ix1 = cumsum(~ix,2)==1;
Wanted = cumsum(ix1,2) .* ...
(ix1 .* s + A)