Help me make my code faster

1 次查看(过去 30 天)
I'm making a grid of 3D positions and using colour to express the number of particles/agents/whatever at that position. Currently I'm using 3 for-loops to cycle through each point and find how many particles at that position. Is there a more MATLAB way to do this using indices or quicker functions? Full code attached, important bit below:
% lim = 6
% LIMS = -lim:lim
[xm,ym,zm] = meshgrid(LIMS,LIMS,LIMS);
density = ones(2*lim+1,2*lim+1,2*lim+1); % 2n+1 to capture entirety of LIMS. (-6 to 6 spans 2*6+1 points)
for a = [10 20] % outermost for-loop because I want to capture probability at two separate time steps, namely t=10 and t=20.
for i = LIMS
for j = LIMS
for k = LIMS
% i+lim+1 translates -6:6 -> 1:13
density(i+lim+1,j+lim+1,k+lim+1) = sum(ismember(A(:,:,a),[i j k],'rows'));
% ^^ this ^^ bit counts how many agents, from A, have that exact position.
% A is 100000 x 3, with 100 sheets (one per timestep).
% That's 100,000 agents, where the first column is x dimension, second is y, third is z of course.
end
end
end
figure; slice(xm,ym,zm,density,0,0,0);
colormap('hot'); grid minor;
end
The full story is that I'm trying to simulate 100,000 agents starting at the origin and propagating outwards in 1,2,3,4, ... dimensions, with an equal probability of moving in any one direction. This'll just help me visualise this distribution in 3D.

采纳的回答

Guillaume
Guillaume 2019-11-5
Unless I'm misreading your code, you're simply computing the histogram of the rows of A. So, assuming that A is made up solely of integers in the set LIM, then:
for a = [10 20]
density = accumarray(A(:, :, a) + lim + 1, 1, repelem(2*lim+1, 3));
%plotting code
end
  11 个评论
Guillaume
Guillaume 2019-11-6
Well, it would be 2*lim+1 x 2*lim+1 x 2*lim+1 matrix giving you the area of each bin. Of course, if all the bins have the same area, the original formula works and you don't need to bother with that.
Gilad Gur Harush
Gilad Gur Harush 2019-11-6
Thought so but good to know anyway thank you :)

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Descriptive Statistics 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by