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!