Optimising code to get matrix indices based on point coordinates
1 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(2 个)
Matt J
2015-8-1
编辑:Matt J
2015-8-1
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);
Matt J
2015-8-1
编辑:Matt J
2015-8-1
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!