How can I index a matrix using an array?

조회 수: 3 (최근 30일)
Yizhuang Alden Cheng
Yizhuang Alden Cheng 2019년 7월 31일
편집: Yizhuang Alden Cheng 2019년 7월 31일
Hi,
I want to create a very large logical matrix, and I have an array which has the indices of the matrix which I want to be true (with the remaining entries being false).
For example, suppose I had the following array 8x2 array:
idx = [1 1;
1 2;
3 1;
3 3;
4 2;
5 1;
5 2;
5 3];
where each row represents index for a 5x3 matrix, and I want to use this array to create the following index:
A = [1 1 0;
0 0 0;
1 0 1;
0 1 0;
1 1 1];
Is there an efficient way to do this without using loops (since in my actual application, A may have something like 1,000,000 rows and 10,000 columns)? Thanks!

채택된 답변

madhan ravi
madhan ravi 2019년 7월 31일
A = accumarray(idx,1,[],[],0)
  댓글 수: 2
Alex Mcaulley
Alex Mcaulley 2019년 7월 31일
nice solution +1
Yizhuang Alden Cheng
Yizhuang Alden Cheng 2019년 7월 31일
Thank you! I had to turn this into a logical matrix after using this code, but nonetheless this a very elegant answer.

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

추가 답변 (1개)

Andrei Bobrov
Andrei Bobrov 2019년 7월 31일
s = max(idx);
A = false(s);
A(sub2ind(s,idx(:,1),idx(:,2))) = true;
  댓글 수: 1
Yizhuang Alden Cheng
Yizhuang Alden Cheng 2019년 7월 31일
편집: Yizhuang Alden Cheng 2019년 7월 31일
Thank you! This works very well, and is in fact faster. I would have accepted this as well if I could accept multiple answers.

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

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by