vectorization of nested for loop

조회 수: 1 (최근 30일)
chabani mohammed ali
chabani mohammed ali 2020년 11월 15일
댓글: chabani mohammed ali 2020년 11월 15일
i want to transfer an image pixels coordination into matrix (rows x 2) , this is the code with for loops, i want to vectorize it because it takes so much time for big images.
I=imread('1.bmp');
[rows,columns,~]=size(I);
pix_im=[];
for l=1:rows
for c=1:columns
pix_im=[pix_im;l c];
end
end

채택된 답변

Ameer Hamza
Ameer Hamza 2020년 11월 15일
편집: Ameer Hamza 2020년 11월 15일
No wonder this code runs slow. You are using dynamic memory allocation. You can get several-fold speed gain just by pre-allocation: https://www.mathworks.com/help/matlab/matlab_prog/preallocating-arrays.html. However, you don't even need a loop for this. You can do it much more efficiently like this.
I=imread('1.bmp');
[rows,columns,~]=size(I);
[c,r] = ndgrid(1:columns, 1:rows);
pix_im = [r(:) c(:)]
  댓글 수: 3
Ameer Hamza
Ameer Hamza 2020년 11월 15일
I am glad to be of help!

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

추가 답변 (0개)

카테고리

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