Replace value with index in 2D array

27 次查看(过去 30 天)
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 个评论
Tha saliem
Tha saliem 2017-4-3
Yes got it. @dpb & @Star Strider Thank you so much for solution it really helped.

请先登录,再进行评论。

更多回答(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)

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

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

尚未输入任何标签。

Community Treasure Hunt

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

Start Hunting!

Translated by