Replacing elements in matrix
조회 수: 1 (최근 30일)
이전 댓글 표시
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?
댓글 수: 0
답변 (1개)
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
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 Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!