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);
1 件のコメント
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!