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

 Réponse acceptée

Ameer Hamza
Ameer Hamza le 15 Nov 2020
Modifié(e) : Ameer Hamza le 15 Nov 2020

0 votes

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 commentaires

chabani mohammed ali
chabani mohammed ali le 15 Nov 2020
Modifié(e) : chabani mohammed ali le 15 Nov 2020
thank you so much it works and it's fast just like i want.
i was trying to do the same thing with meshgrid but i couldn't get a correct result ( am new to matlabe),
and even when i use a loop with pre-allocation the way you proposed is faster. thank you again.
Ameer Hamza
Ameer Hamza le 15 Nov 2020
I am glad to be of help!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange

Produits

Version

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by