Question about assigning value in a matrix.

조회 수: 7 (최근 30일)
C Zeng
C Zeng 2013년 6월 6일
Hi, all, again, I want to do the work quickly: I have a large matrix A, and I want to assign value in some entry in each row.
For example:
A=zeros(4);
a=[1,2;
2,3;
3,2;
4,1];
I want (1,2), (2,3),(3,2), (4,1) of matrix A be 1. How shall I make it work in no more than 3 commands?
What I am doing now is using loops:
for i=1:4
A(a(i,1),a(i,2)=1;
end
However, as i is very large like 3^14, the program is very slow. So I wonder is there a way to speed the programming?
Thanks.

채택된 답변

Walter Roberson
Walter Roberson 2013년 6월 6일
idx = sub2ind(size(A), [1 2 3 4], [2 3 2 1]);
A(idx) = 1;
  댓글 수: 3
Sean de Wolski
Sean de Wolski 2013년 6월 6일
I've always found for-loops to be significantly faster than sub2ind and ind2sub. Especially as the number of indices gets large.
It's been a few years since I was timing it for my own work though...
C Zeng
C Zeng 2013년 6월 6일
Oh, really? I always found that MATLAB is not efficient for large loops. That is why I tried to avoid large loops.

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

추가 답변 (2개)

Azzi Abdelmalek
Azzi Abdelmalek 2013년 6월 6일
A=zeros(4);
a=[1,2;
2,3;
3,2;
4,1];
idx= sub2ind(size(A),a(:,1),a(:,2));
A(idx)=1

Sean de Wolski
Sean de Wolski 2013년 6월 6일
I've always found for-loops to be significantly faster than sub2ind and ind2sub. Especially as the number of indices gets large.
It's been a few years since I was timing it for my own work though...
  댓글 수: 12
C Zeng
C Zeng 2013년 6월 7일
Thanks, Sean!
Let me try it again. I have to run large data on server, because 3^12 is memory out here.
C Zeng
C Zeng 2013년 6월 13일
Sean, thanks for your advice. My program got speedup. sub2ind will be faster if the size is large.

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

카테고리

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