Replacing elements in matrix
2 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Réponses (1)
David Hill
le 16 Juil 2020
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 commentaires
David Hill
le 21 Juil 2020
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.
Voir également
Catégories
En savoir plus sur Resizing and Reshaping Matrices dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!