Replacing elements in matrix

1 visualizzazione (ultimi 30 giorni)
Rabia Zulfiqar
Rabia Zulfiqar il 16 Lug 2020
Commentato: David Hill il 21 Lug 2020
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?

Risposte (1)

David Hill
David Hill il 16 Lug 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 Commenti
Rabia Zulfiqar
Rabia Zulfiqar il 18 Lug 2020
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 il 21 Lug 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.

Accedi per commentare.

Community Treasure Hunt

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

Start Hunting!

Translated by