Borrar filtros
Borrar filtros

speed up a code, subindex for 4-d matrix?

4 visualizaciones (últimos 30 días)
MementoMori
MementoMori el 4 de Abr. de 2023
Respondida: Rasmita el 14 de Abr. de 2023
Hi, in my code I need to do this operation,
for a = 1:h
for b = 1:h
ind=sub2ind(size(I), centriX+a - h/2, centriY+ b - h/2);
A(:,:,a,b) = (I(ind));%*gamma1;
end
end
where I is a 2D matrix, "centriX" and "centriY" are 2D matrices that contains the coordinates of some centers that I am interested in.
Is there any way not to use for loops?
I have uploaded the files of "centriX" and "centriY".
Matrix "I" is too heavy, but you can take a random matrix (5200x5200). h=40
  2 comentarios
Dyuman Joshi
Dyuman Joshi el 4 de Abr. de 2023
It is difficult to comment without the data. Can you copy-paste or attach your data? To attach, save the data as a .mat file and use the paper clip button.
MementoMori
MementoMori el 4 de Abr. de 2023
I have edited the question

Iniciar sesión para comentar.

Respuestas (1)

Rasmita
Rasmita el 14 de Abr. de 2023
Hi,
It is my understanding that you are trying to rewrite the above code without using loops. You can use the bsxfun function in MATLAB to compute the required indices for all combinations of a and b in one go, without using loops.
In the first step, you can create the indices ‘a’ and ‘b’ relative to the center point. In the second step, you can use bsxfun to add these indices to the corresponding elements of centriX and centriY, resulting in a 4D array of shape (numel(centriX), numel(centriY), h, h) containing the indices for all combinations of a and b. Finally, extract the values from matrix ‘I using linear indexing, then reshape the result to the desired shape, and assign it to A.
For more information, please refer to the below documentation links:
Hope this helps!
Regards,
Rasmita

Categorías

Más información sobre Operating on Diagonal Matrices en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by