MATLAB Answers

Replace numbers in a matrix depending on if statements from arrays

3 ビュー (過去 30 日間)
Per Vatsvag
Per Vatsvag 2020 年 6 月 10 日
コメント済み: Per Vatsvag 2020 年 6 月 10 日
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.

採用された回答

madhan ravi
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)
  1 件のコメント
Per Vatsvag
Per Vatsvag 2020 年 6 月 10 日
Dear madhan ravi,
Thank you for your help

サインインしてコメントする。

その他の回答 (2 件)

Ameer Hamza
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;

rajkumar k
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

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by