Replace value with index in 2D array

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

 採用された回答

Star Strider
Star Strider 2017 年 4 月 3 日

0 投票

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 件のコメント

Tha saliem
Tha saliem 2017 年 4 月 3 日
Thankyou so much. but why original matrix changes in output?
dpb
dpb 2017 年 4 月 3 日
'Cuz (like mine)
A(address)=assignment
is assigning into the original A; we presumed the idea was to replace elements.
If want new and retain A, just
B(A==1)=j;
will create B using the same logical addressing expression for positions and since A==1 returns a logical array same size as A, B will be the same size as A.
Star Strider
Star Strider 2017 年 4 月 3 日
My pleasure.
The original matrix does not have to change. It has to be duplicated in the ‘result’ matrix if you do not want ‘A’ to change:
A=[0 0 1; 1 0 1; 0 1 0];
result = A;
[~,CIV] = find(result); % ‘CIV’ = ‘Column Index Value’
result(result>0) = CIV
Tha saliem
Tha saliem 2017 年 4 月 3 日
Yes got it. @dpb & @Star Strider Thank you so much for solution it really helped.
Star Strider
Star Strider 2017 年 4 月 3 日
Our pleasure!

サインインしてコメントする。

その他の回答 (2 件)

Jan
Jan 2017 年 4 月 3 日
編集済み: Jan 2017 年 4 月 3 日

2 投票

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 件のコメント

Stephen23
Stephen23 2017 年 4 月 3 日
+1 nice.
Tha saliem
Tha saliem 2017 年 4 月 3 日
Good one. Thanks alot @Jan Simon

サインインしてコメントする。

dpb
dpb 2017 年 4 月 3 日

0 投票

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

カテゴリ

ヘルプ センター および File ExchangeCreating and Concatenating Matrices についてさらに検索

タグ

タグが未入力です。

Community Treasure Hunt

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

Start Hunting!

Translated by