Replace value with index in 2D array

27 vues (au cours des 30 derniers jours)
Tha saliem
Tha saliem le 3 Avr 2017
Commenté : Star Strider le 3 Avr 2017
Hi I have a 2D array like this
A=[0 0 1; 1 0 1; 0 1 0]
I want to replace 1 in each row with column index value. e.g new matrix will be like this:
result=[0 0 3 ; 1 0 3 ; 0 2 0]
Thanks in advance

Réponse acceptée

Star Strider
Star Strider le 3 Avr 2017
This works:
A=[0 0 1; 1 0 1; 0 1 0];
[~,CIV] = find(A); % ‘CIV’ = ‘Column Index Value’
A(A>0) = CIV
result = A
result =
0 0 3
1 0 3
0 2 0
  5 commentaires
Tha saliem
Tha saliem le 3 Avr 2017
Yes got it. @dpb & @Star Strider Thank you so much for solution it really helped.
Star Strider
Star Strider le 3 Avr 2017
Our pleasure!

Connectez-vous pour commenter.

Plus de réponses (2)

Jan
Jan le 3 Avr 2017
Modifié(e) : Jan le 3 Avr 2017
A version without FIND:
A = [0 0 1; 1 0 1; 0 1 0];
R = A .* (1:3); % Auto expanding in >= R2016b
In older Matlab versions:
R = bsxfun(@times, A, 1:3)
  2 commentaires
Stephen23
Stephen23 le 3 Avr 2017
+1 nice.
Tha saliem
Tha saliem le 3 Avr 2017
Good one. Thanks alot @Jan Simon

Connectez-vous pour commenter.


dpb
dpb le 3 Avr 2017
>> [~,j]=find(A);
>> A(A==1)=j
A =
0 0 3
1 0 3
0 2 0
>>

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Tags

Aucun tag saisi pour le moment.

Community Treasure Hunt

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

Start Hunting!

Translated by