Efficiently finding equal neigbors in arrays.
24 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
I project I'm currently working on requires me to check if arrays (contained in cell arrays ) contain neighboring elements that are equal, and if they are pass the position of the first of these two elements to some nested function. I noticed that my naive approach to doing this is one of the bottlenecks of my code currently (because this piece of code is being called extremely often during my simulations). What is the most efficient way to handle this?
Here are some more details about my code:
My code needs to deal with a cell array X, each cell of which is itself a cell array, containing a (d,2) double array where the value of d can vary. For example, X could look as follows:
X = cell(N,1);
for i=1:N
X{i}=cell(1,10);
for j=1:10
d = randi(50);
X{i}{j} = randi(10, d,2); %each cell contains a double array of size (5,2)
end
end
I need check if any array X{i}{j} contains two rows where the first collumn is equal, and pass the position of the first row of each such pair to some function. I do this as follows:
for i=1:N
Xi = X{i}
for j=1:10
for k = 1:size(Xi{j},1)-1
if Xi{j}(k,1) == Xi{j}(k+1)
MyNestedFunction(i,j,k); % a nested function that modifies X
end
end
end
end
While profiling my code, I noticed that most time is spent on the line containing the inner most forloop for k=1:size(X{i}{j},1)-1. Is there a way to make this more efficient?
I also tried using
for i=1:N
Xi = X{i}
for j=1:10
for k = find(diff(Xi{j}(1:size(Xi{j},1)))==0)
MyNestedFunction(i,j,k); % a nested function that modifies X
end
end
end
but this is actually slower than my first attempt.
0 commentaires
Réponses (1)
David Hill
le 25 Août 2020
for i=1:N
Xi = X{i}
for j=1:9
m=min([size(X{i}{j},1),size(X{i}{j+1},1)]);
k=find(X{i}{j}(1:m,1)]),1)-X{i}{j+1}(1:m,1)==0);
MyNestedFunction(i,j,k);
end
end
4 commentaires
David Hill
le 27 Août 2020
for i=1:N
Xi = X{i};
for j=1:10
k=find(diff(X{i}{j}(:,1))==0);
MyNestedFunction(i,j,k);
end
end
Voir également
Catégories
En savoir plus sur Multidimensional Arrays dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!