ismember matlab function too slow

6 次查看(过去 30 天)
Hi, I would love some help optimizing this piece of code.
In my model i have to go every time instant through all the pixels of an image ( this cannot be changed to solve the equations that I want).
At a given step I want to now if a given pixel corresponds to the list of upetake indexes (uptake_indices) or not. If so I would have a concentration = uptake, else it would be 0.
Currently I am using ismember, but since my arrays are big and the loops are really long, this step delays a lot my code.
Here is a pice of my code.
Thanks for the help!
% list of indexes of my 400x400 image
aux=1;
pareja_indice=zeros(400*400,1);
for i=1:400
for j=1:400
pareja_indice(aux) = sub2ind([400, 400], i, j);
aux=aux+1;
end
end
% Load indexes corresponding to uptake points in the image
load('GABA_uptake_points3.mat');
uptake_indices = sub2ind([400, 400], SourceY, SourceX);
aux=0;
uptake=30;
% initialize concentration matrix
C=zeros(400,400);
for k=1:2000000
% other operations
for i=1:400
for j=1:400
aux=aux+1;
% we should only have uptake at the uptake locations
C_up = uptake * ismember(pareja_indice(aux), uptake_indices);
C(i,j)=C_up;
% ... other operations
end
end
% other operation
end

采纳的回答

Hitesh
Hitesh 2024-10-11
编辑:Hitesh 2024-10-11
Hi Paula Giménez Mínguez,
From the code snippet, what I understand that you are determining if a pixel index matches an uptake index, which is loaded from the "GABA_uptake_points3.mat" file using the SourceY and SourceX variables. By transforming uptake_indices into a logical array, you can efficiently identify whether each pixel is an uptake point. This method enables direct indexing, offering a significant improvement in elapsed time over repeatedly using ismember.
Refer to the below code :
tic;
% List of indexes of the 400x400 image
pareja_indice = reshape(1:(400*400), [400, 400]);
% Load indexes corresponding to uptake points in the image
load('GABA_uptake_points3.mat');
uptake_indices = sub2ind([400, 400], SourceY, SourceX);
% Create a logical array to identify uptake points
uptake_mask = false(400, 400);
uptake_mask(uptake_indices) = true;
% Initialize concentration matrix
uptake = 30;
C = zeros(400, 400);
for k = 1:2000000
% Only perform operations on uptake points
C(uptake_mask) = uptake;
% ... other operations
end
toc;
For more information on logical array, refer to this MATLAB documentation: https://www.mathworks.com/help/matlab/ref/logical.html
Hope this helps!!
  1 个评论
Paula Giménez Mínguez
移动:Bruno Luong 2024-10-11
Thank you so much!
Indeed, finally I did something very similar and it reduced importantly the elapse time. What it took days of runing now is just a couple of hours.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Elementary Polygons 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by