Optimising code to get matrix indices based on point coordinates
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
I have the code
xnum = 600; xstp = 1/(xnum-1); xgrid = 0:xstp:1;
ynum = 600; ystp = 1/(ynum-1); ygrid = 0:xstp:1;
xystp = xstp;
nums = 100000;
O=rand(ynum,xnum);
for i=1:1000
x=rand(nums,1);
y=rand(nums,1);
elposx = x./xystp;
elposy = y./xystp;
elposx = round(elposx);
elposy = round(elposy);
pos_ind = round(elposx.*ynum+elposy+1); % indices for element positions
Onew = O(pos_ind)
end
So, the idea is to use the coordinates (x,y), which represent the positions of points within the a matrix of size (xnum,ynum), to get the indices of the nearest element in the matrix. Then, using those indices, sample any matrix of this size (e.g. "O").
The above is the fastest I have been able to get it. This computation represents about 85% of the work of my total code, so it is a significant bottleneck. Is there a way to do these computations faster? Different functions? Parfors? GPU?
Any help is appreciated.
0 Kommentare
Antworten (2)
Matt J
am 1 Aug. 2015
Bearbeitet: Matt J
am 1 Aug. 2015
No need to loop, as far as I can see. Also, no need to round() the calculation of pos_ind. It's all integer arithmetic,
numO=1000;
x=rand(nums,numO);
y=rand(nums,numO);
elposx = round( x*(xnum-1)+1 );
elposy = round( y*(ynum-1)+1 );
pos_ind = sub2ind([ynum,xnum],elposy,elposx); % indices for element positions
Onew = reshape(O(pos_ind),xnum,ynum,numO);
1 Kommentar
Matt J
am 1 Aug. 2015
Bearbeitet: Matt J
am 1 Aug. 2015
Using griddedInterpolant might be better. Should rely on more optimized builtin code, at least to do the rounding of the coordinates,
[m,n]=size(O);
F=griddedInterpolant(O,'nearest');
for i=1:1000
x = rand(nums,1)*(m-1)+1;
y = rand(nums,1)*(n-1)+1;
Onew=F(x,y);
end
Further acceleration is possible for this example using PARFOR, but since your true code isn't available, hard to say if it's parfor-compatible.
0 Kommentare
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!