Replace value with index in 2D array

66 ビュー (過去 30 日間)
Tha saliem
Tha saliem 2017 年 4 月 3 日
コメント済み: Star Strider 2017 年 4 月 3 日
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 日
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 件のコメント
Star Strider
Star Strider 2017 年 4 月 3 日
Our pleasure!

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

その他の回答 (2 件)

Jan
Jan 2017 年 4 月 3 日
編集済み: Jan 2017 年 4 月 3 日
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 件のコメント
Tha saliem
Tha saliem 2017 年 4 月 3 日
Good one. Thanks alot @Jan Simon

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


dpb
dpb 2017 年 4 月 3 日
>> [~,j]=find(A);
>> A(A==1)=j
A =
0 0 3
1 0 3
0 2 0
>>
  1 件のコメント
Tha saliem
Tha saliem 2017 年 4 月 3 日
Thanks Alot.

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

タグ

タグが未入力です。

Community Treasure Hunt

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

Start Hunting!

Translated by