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?
'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.
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 Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

태그

아직 태그를 입력하지 않았습니다.

질문:

2017년 4월 3일

댓글:

2017년 4월 3일

Community Treasure Hunt

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

Start Hunting!

Translated by