Replace numbers in a matrix depending on if statements from arrays
1 次查看(过去 30 天)
显示 更早的评论
Dear all Community members,
I have a 5x5 matrix and two arrays (1x5 and 5x1) 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.
0 个评论
采纳的回答
madhan ravi
2020-6-10
编辑:madhan ravi
2020-6-10
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)
更多回答(2 个)
Ameer Hamza
2020-6-10
编辑:Ameer Hamza
2020-6-10
This is one of the solutions. A more direct solution is probably possible,
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];
thresh = 3.1*sqrt(h);
mask1 = A > thresh;
mask2 = ~[zeros(size(A,1), 1) mask1(:, 1:end-1)];
mask = mask1.*mask2;
B = cumsum(A.*mask2, 2).*mask;
A_new = (A.*~mask + B).*mask1;
0 个评论
rajkumar k
2020-6-10
Try this code:
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];
[ta tb]=size(t);
for i = 1:size(h)
for j = 1:tb
thres(i,j)=3.1*sqrt(h(i))
end
end
for i=1:size(h)
b=0;
for j=1:tb
if A(i,j)<=thres(i,j)
b=A(i,j)+b;
B(i,j)=0;
else
B(i,j)=b+A(i,j);
end
end
end
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!