Replace value with index in 2D array

16 views (last 30 days)
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

Accepted Answer

Star Strider
Star Strider on 3 Apr 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 Comments
Tha saliem
Tha saliem on 3 Apr 2017
Yes got it. @dpb & @Star Strider Thank you so much for solution it really helped.

Sign in to comment.

More Answers (2)

Jan
Jan on 3 Apr 2017
Edited: Jan on 3 Apr 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)

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

Categories

Find more on Resizing and Reshaping Matrices in Help Center and File Exchange

Tags

No tags entered yet.

Community Treasure Hunt

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

Start Hunting!