필터 지우기
필터 지우기

Replace numbers in a matrix depending on if statements from arrays

조회 수: 2 (최근 30일)
Askeladden2
Askeladden2 2020년 6월 10일
댓글: Askeladden2 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)

추가 답변 (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

카테고리

Help CenterFile Exchange에서 Multidimensional Arrays에 대해 자세히 알아보기

제품


릴리스

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by