Fastest way for variable row indexing
조회 수: 14 (최근 30일)
이전 댓글 표시
Hi all, I am trying to speed up my code, but cannot find a faster way than a loop and I think there should be one (probably). So the problem is the following: I have a 2D array V and need to set a variable amount of consecutive columns to A and the rest to B (for simplicity). Variable means each row is different and up to where each row has to be set to A is stored in L. So currently it looks like this:
for c = 1 : size(V,1)
V(c,:) = [repmat(A,1,L(c)) repmat(B,1,size(V,2)-L(c))]
end
So does anyone know a faster solution? If the index would be identical per row it would be easily achievable using repmat or bsxfun, but I could not figure out a way to use indices of different length for every row of the matrix. Same for sub2ind which only seems to work if the indices per row have the same length. Btw., only speed matters, the solution can be ugly ;) Any help would be greatly appreciated!
댓글 수: 2
Image Analyst
2017년 3월 19일
Give a small numerical example with values for L, V, B, and A. Also let us know what version of MATLAB you have, especially if it's R2016b or later.
답변 (2개)
Philip Borghesani
2017년 3월 19일
I made two changes to your code on my machine it is a bit faster:
- Avoid using repmat and concatination instead use direct assignment.
- Work with a transposed matrix and transpose when done.
The second change will help more or less depending on the image size and processor memory caching configuration. Larger images will make a bigger difference.
A = 1;
B = 2;
L = ceil(rand(1,2000)*1000);
V = nan(1000,2000);
tic
for c = 1 : size(V,2)
V(1:L(c),c) = A;
V(L(c)+1:end,c) = B;
end
V=V';
toc
imagesc(V)
댓글 수: 2
Walter Roberson
2017년 3월 20일
댓글 수: 3
Walter Roberson
2017년 3월 24일
%these can be set up ahead of time
M = 200; N = 100;
T = 1 : N;
%you could change these each loop iteration if desired
A = 1;
B = 2;
%if A and B are constant you could initialize this outside the loop
W = A + zeros(M, N);
%this would be done each loop, for sure.
L = ceil(rand(M,1)*N);
V = W;
V( bsxfun( @lt, L, T) ) = B; %your one-liner.
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!