Efficiently finding equal neigbors in arrays.

1 次查看(过去 30 天)
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.

回答(1 个)

David Hill
David Hill 2020-8-25
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 个评论
AS
AS 2020-8-27
No, you are comparing X{i}{j}(m,1) with X{i}{j+1}(m,1) instead of comparing X{i}{j}(m,1) with X{i}{j}(m+1,1).
David Hill
David Hill 2020-8-27
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

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品


版本

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by