Speedup table lookup / interpolation

2 次查看(过去 30 天)
Hi, for AI Q-learning I need to interpolate a found state to a table of states to determine a next action.
states_list is a Nx4 matrix (N is in order of 1e6), state is a 1x4 array. I need to find the row (state_index) in the state_list that is the nearest to the state. The function below works, but is far to slow for my goal.
Any suggestions to improve the performance of this function?
function state_index = interpolate_states(states_list, state)
error = abs(states_list(:,1)-state(1))+abs(states_list(:,2)-state(2))+abs(states_list(:,3)-state(3))+abs(states_list(:,4)-state(4));
[~,state_index] = min(error);
end

回答(1 个)

dpb
dpb 2021-8-1
编辑:dpb 2021-8-1
Slight alteration; didn't try to time it...
[~,ix]=min(sum(abs(states_list-state),2));
is same computationally...
>> x=randi(10,4); y=1:4; % some test data
>> e=0;for i=1:4,e=e+abs(x(:,i)-y(i));end % emulated current solution
>>> all(e==sum(abs(x-y),2)) % compare to vector solution
ans =
logical
1
>>
I wouldn't think it would make a noticeable difference in execution speed and I've never tested it to see if does matter, but you could consider reorienting the data to be by row instead of by column and so are 4 x N and 4x1; this would let sum work in its natural order by column removing the optional second argument.
Another slight overhead reduction might be to write the above inline instead of calling a function for a one-liner...
  2 个评论
Jurrien Plijter
Jurrien Plijter 2021-8-3
The differences are marginal, but still thank you for your time!
dpb
dpb 2021-8-3
编辑:dpb 2021-8-3
Which alternative(s) did you test? The memory orientation one would turn addressing into linear sequence order instead of skipping although since is inside compiled code probably not make a whole lot of difference. Who knows, the JIT may be smart enough to transpose internally, anyway.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Interpolation 的更多信息

标签

产品


版本

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by