Replacing elements in matrix

조회 수: 1 (최근 30일)
Rabia Zulfiqar
Rabia Zulfiqar 2020년 7월 16일
댓글: David Hill 2020년 7월 21일
I have a matrix A.For example
[0 0 0 0 ;
1 2 1 2 ;
2 0 0 -1 ;
-1 0 -1 -2 ;
-2 -2 -2 0]
Now the query is I have find those columns where there is a mismatch between positive and negative values.For example in column 1 there is no mismatch as we have two positive values and 2 negative values,similarly in column 2 there is no mistmatch because one positive value and one negative value but in column 3 and 4 there is a mismatch where only one positive value is there and two negative values.So now what I want to do is remove the extra negative value.Like in column 3 the postive value is 1 so the negative value should be -1 and -2 should be replaced by zero.Same goes for column 4. I already know the index of rows where there is a mismatch and I have this array B=[3,4] where 3 and 4 indicates the index of columns where there is a mismatch. The result matrix should be [0 0 0 0 ; 1 2 1 2 ; 2 0 0 0 ; -1 0 -1 -2 ; -2 -2 0 0] How can I do this?

답변 (1개)

David Hill
David Hill 2020년 7월 16일
a=[0 0 0 0 ; 1 2 1 2 ; 2 0 0 -1 ; -1 0 -1 -2 ; -2 -2 -2 0];
b=sum(a>0)-sum(a<0);
for k=1:length(b)
if b(k)<0
for m=1:abs(b(k))
a(find(a(:,k)<0,1,'last'),k)=0;
end
elseif b(k)>0
for m=1:b(k)
a(find(a(:,k)>0,1,'last'),k)=0;
end
end
end
  댓글 수: 2
Rabia Zulfiqar
Rabia Zulfiqar 2020년 7월 18일
Hi @David Hill thankyou for giving an answer but unfortunately it is not giving correct results.
It is giving this answer.
If you see in the forth row -1 should be replaced by zero but here instead of that -2 is replaced by zero according to your code.
David Hill
David Hill 2020년 7월 21일
What is the rule then for deciding what to change to zero if it is not the 'last' in the column? You explained two examples with more negative values, but none where there are more positive values. You need to explain what the rule is for changing excess positive or negative values to zero is.

댓글을 달려면 로그인하십시오.

카테고리

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

태그

Community Treasure Hunt

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

Start Hunting!

Translated by