Increasing the caclulation speed while using loops

1 view (last 30 days)
Dear MATLAB experts,
I considered a range for x and y and if x1 and y1 are within a specific range the code must convert x1 and y1 to the mean value of the specific range.
In other words, considering a pixel and if the values of x and y are inside the pixel, I wanted to replace the values with the position of the center of the pixel as shown in the attached file (if x and y are black corss must be replaced with red one)
Code is working but as the data is very big, the calculation speed is slow. Is there any modifications that may lead to increase the speed of calculations?
Thank you in advance.
data = load('data.mat').out1_com;
det_x = 50;
det_y = 50;
det_ch = 16;
%%
xedges = -(det_x/2):(det_x/det_ch):(det_x/2);
yedges = -(det_y/2):(det_y/det_ch):(det_y/2);
kf = data(:,1);
x1 = data(:,2);
y1 = data(:,3);
z1 = data(:,4);
len = length(x1);
x11 = zeros(len,1);
y11 = zeros(len,1);
for k=1:length(x1)
for i = 1:length(xedges)-1
for j = 1:length(yedges)-1
idx1 = (xedges(i) <= x1(k)) & ((x1(k)) < xedges(i+1)) & (yedges(j) <= (y1(k))) & ((y1(k)) < yedges(j+1));
if (idx1 == 1)
x11(k)=(xedges(i)+xedges(i+1)) ./ 2;
y11(k)=(yedges(j)+yedges(j+1)) ./ 2;
end
end
end
end
pos=[kf,x11,y11,z1];
  3 Comments
Stephen23
Stephen23 on 18 Nov 2022
Edited: Stephen23 on 18 Nov 2022
"The problem is I don't want to count the points in each pixel "
You would use the 4th and 5th outputs (bin indices), not the 1st and 2nd outputs (counts).

Sign in to comment.

Accepted Answer

David Goodmanson
David Goodmanson on 17 Nov 2022
Edited: David Goodmanson on 17 Nov 2022
Hi Hamid,
Hi Hamid, I have not speed checked this but it should be faster (the range in your example is different from the drawing).
det_x = 50;
det_y = 50;
det_ch = 16;
%
xedges = -(det_x/2):(det_x/det_ch):(det_x/2)
yedges = -(det_y/2):(det_y/det_ch):(det_y/2);
xmid = (xedges(1:end-1)+xedges(2:end))/2;
ymid = (yedges(1:end-1)+yedges(2:end))/2;
x = -25+50*rand(1,2000); % some data in -25< x,y <25
y = -25+50*rand(1,2000);
xr = round((x+25)*16/50 +1/2);
yr = round((y+25)*16/50 +1/2);
xnew = (xr-1/2)*50/16-25;
ynew = (yr-1/2)*50/16-25;
plot(x,y,'.',xnew,ynew,'o')
  3 Comments

Sign in to comment.

More Answers (0)

Categories

Find more on Data Distribution Plots in Help Center and File Exchange

Products


Release

R2022b

Community Treasure Hunt

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

Start Hunting!