Better way to use circshift

I am trying to create array B from array A (of course in the real application the numbers are not sequential and the arrays are much biggger i.e. 5000x5000)
B =
5 0 1 2 3 4
4 5 0 1 2 3
3 4 5 0 1 2
2 3 4 5 0 1
1 2 3 4 5 0
A =
0 1 2 3 4 5
0 1 2 3 4 5
0 1 2 3 4 5
0 1 2 3 4 5
0 1 2 3 4 5
Here is my solution:
for i = 1:5 B(i,:) = circshift(A(i,:),[0,i]); end
Is there a better (i.e. faster) way to do this? On a more general note, I get the fealing that using a for loop to act on a array is always a bad idea.

댓글 수: 2

Image Analyst
Image Analyst 2012년 11월 1일
Wrong. Using for loops is not always a bad idea.
Brent
Brent 2012년 11월 2일
Thanks for the answers. I didn't realize I would spark a debate. Unfortunatly, my array is not sparse. However, thaks to your comments, I realized that B is just a Toeplitz matrix based on the rows in A (duh ... can't believe I didn't see that). Here is the final code that I came up with:
r = rand(5000,1);
>> A = ones(size(r,1)-1,1)*r';
>> tic;B = toeplitz(fliplr(r'),circshift(r',[0,1]));toc
Elapsed time is 0.474317 seconds.
Not as good as Matt J., but it will do for my purpose. Thanks

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

답변 (2개)

Matt J
Matt J 2012년 11월 1일
편집: Matt J 2012년 11월 1일

0 개 추천

If the matrix is going to be sparse, this should be pretty fast
B=interpMatrix([5 4 3 2 1],1,6,1,'circ');
B(end,:)=[];
Sean de Wolski
Sean de Wolski 2012년 11월 1일

0 개 추천

v = 0:5;
B = gallery('circul',v);
B = B(2:end,:);
A = repmat(v,[numel(v)-1,1]);

댓글 수: 3

Matt J
Matt J 2012년 11월 1일
Careful. GALLERY has had a hard time producing large sparse circulant matrices, as discussed here
Don't know if they fixed this in more recent MATLAB versions...
tic,B = gallery('circul',1:5000);toc
Elapsed time is 0.603616 seconds.
It seems to be doing better in terms of memory management, compared to past MATLAB versions, but it's still slow. Take the example from my link. In R2012a, I get these timings:
r=[1 2 3 4 sparse(zeros(1,10000))];
tic; A=gallery('circul',r); toc
Elapsed time is 4.887724 seconds.
tic; A=interpMatrix(r,1,length(r),1,'circ').'; toc
Elapsed time is 0.005704 seconds.

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

카테고리

도움말 센터File Exchange에서 Data Type Identification에 대해 자세히 알아보기

질문:

2012년 11월 1일

Community Treasure Hunt

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

Start Hunting!

Translated by