필터 지우기
필터 지우기

Removing nested for loops for quicker time

조회 수: 1 (최근 30일)
Sanghyun Lee
Sanghyun Lee 2019년 9월 11일
댓글: Bob Thompson 2019년 9월 12일
I need help removing the nested for loop in this code.
The code right now has imagesList, totalDistance which are 4D arrays, and finalPixels is a 3D array and index is a 2D array.
The code goes through each of the rows and columns to replace them with colours in the finalPixels which are each stored in its own 2D array which (:,:,1) is red (:,:,2) is green and (:,:,3) is blue.
[~,index]=max(totalDistance,[],4);
[rows,cols]=size(index);
finalPixels=zeros(rows,cols,3);
for i=1:rows
for j=1:cols
finalPixels(i,j,1)=imagesList(i,j,1,index(i,j));
finalPixels(i,j,2)=imagesList(i,j,2,index(i,j));
finalPixels(i,j,3)=imagesList(i,j,3,index(i,j));
end
end

답변 (2개)

Bob Thompson
Bob Thompson 2019년 9월 11일
I'm shooting in the dark a bit on this one, but I think you can get rid of both loops. The only thing I'm not entirely sure about is whether the indexing for the max 4th dimension value will work correctly.
finalPixels(:,:,1:3)=imagesList(:,:,1:3,index);
Without a sample of data I wouldn't be able to test it, but feel free to post any problems you have.
  댓글 수: 2
Sanghyun Lee
Sanghyun Lee 2019년 9월 12일
doens't seem to work
the error i get is this:(its translated so it might be wrong)
The requested 557x495x3x275715 (212.4 GB) array exceeds the maximum array size preference. If you create an array that is larger than this limit, it can take a long time and MATLAB may stop responding. For more information, see Array size limit or Preferences panel.
Bob Thompson
Bob Thompson 2019년 9월 12일
Ok, so it's trying to use each of the elements in the 2D index array. I thought that might happen, but I had hoped it wouldn't. Unfortunately, I cannot think of another way to avoid using loops. It doesn't mean it doesn't exist, I just don't know it.

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


Bruno Luong
Bruno Luong 2019년 9월 11일
편집: Bruno Luong 2019년 9월 11일
I know
  1. totalDistance third dimension is a singleton
  2. p, the third dimension imagesList of is 3, and
  3. other dimensions of totalDistance and imagesList match
which are all important piece of information and you must learn to clearly state when asking question for people who can understand
[~,index] = max(totalDistance,[],4);
[m,n,p,~] = size(imagesList);
x = m*n*p;
finalPixels = reshape(imagesList((1:x)'+x*(repmat(index(:)-1,p,1))),[m,n,p]);

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품


릴리스

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by