Optimising code to get matrix indices based on point coordinates
1 visualizzazione (ultimi 30 giorni)
Mostra commenti meno recenti
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 Commenti
Risposte (2)
Matt J
il 1 Ago 2015
Modificato: Matt J
il 1 Ago 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 Commento
Matt J
il 1 Ago 2015
Modificato: Matt J
il 1 Ago 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 Commenti
Vedere anche
Categorie
Scopri di più su Loops and Conditional Statements in Help Center e File Exchange
Prodotti
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!