필터 지우기
필터 지우기

How to access specific elements of an array?

조회 수: 1 (최근 30일)
Karthik Nagarajan
Karthik Nagarajan 2017년 7월 14일
댓글: Star Strider 2017년 7월 14일
Suppose I have two matrices A and x as follows:
x =
1 2
2 3
A =
1 1 1 1
1 1 1 1
1 1 1 1
1 1 1 1
Each row of x contains the row and column indices of an element of A that I would like to access and change. In the above example, I want to change the (1,2) and (2,3) elements of A. Suppose I want to set the value of these elements to 5. The command 'A([1 2],[2 3]) = 5;' produces A =
1 5 5 1
1 5 5 1
1 1 1 1
1 1 1 1
However, what I want is the following:
A =
1 5 1 1
1 1 5 1
1 1 1 1
1 1 1 1
In my actual code, A and x may have thousands of elements each. Therefore, I am wondering whether it is possible to do this without using a for loop?

채택된 답변

Star Strider
Star Strider 2017년 7월 14일
편집: Star Strider 2017년 7월 14일
One approach:
ix = sub2ind(size(A), x(:,1), x(:,2)); % Change Subscripts To Linear Index Vector
A(ix) = 5;
A =
1 5 1 1
1 1 5 1
1 1 1 1
1 1 1 1
  댓글 수: 2
Karthik Nagarajan
Karthik Nagarajan 2017년 7월 14일
Thank you for the quick reply. Exactly what I was looking for!
Star Strider
Star Strider 2017년 7월 14일
As always, my pleasure!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by