# Increasing the caclulation speed while using loops

조회 수: 1(최근 30일)
Hamid 2022년 11월 17일
편집: Stephen23 2022년 11월 18일
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?
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표시숨기기 이전 댓글 수: 2
Stephen23 2022년 11월 18일
편집: Stephen23 2022년 11월 18일
"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).

댓글을 달려면 로그인하십시오.

### 채택된 답변

David Goodmanson 2022년 11월 17일
편집: David Goodmanson 2022년 11월 17일
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표시숨기기 이전 댓글 수: 2
Hamid 2022년 11월 18일
Hi David,
I see. Thanks a lot!

댓글을 달려면 로그인하십시오.

### 범주

Find more on Matrix Indexing in Help Center and File Exchange

R2022b

### Community Treasure Hunt

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

Start Hunting!