快速意味着比 O(N) 更好,这与 find() 的能力一样好。我知道有ismembc
and ismembc2
,但我认为它们都不是我正在寻找的。我阅读了文档,他们似乎正在寻找会员equal到 x,但我想要索引第一个值较大 than x.
现在如果这些函数中的任何一个is有能力做到这一点,有人可以举个例子吗,因为我无法弄清楚。
理想的行为:
first_greater_than([0, 3, 3, 4, 7], 1)
返回 2,即第一个大于 1 的值的索引,但显然输入数组会大得多。
当然,二分查找实现起来并不是太难,但是如果MATLAB已经做到了,我宁愿使用他们的方法。
由于输入已经排序,自定义二分搜索应该可以工作(您可能需要对边缘情况进行一些更新,i.e请求的值小于数组的所有元素):
function [result, res2] = binarySearchExample(val)
%// Generate example data and sort it
N = 100000000;
a = rand(N, 1);
a = sort(a);
%// Run the algorithm
tic % start timing of the binary search algorithm
div = 1;
idx = floor(N/div);
while(1)
div = div * 2;
%// Check if less than val check if the next is greater
if a(idx) <= val,
if a(idx + 1) > val,
result = a(idx + 1);
break
else %// Get bigger
idx = idx + max([floor(N / div), 1]);
end
end
if a(idx) > val, % get smaller
idx = idx - floor(N / div);
end
end % end the while loop
toc % end timing of the binary search algorithm
%% ------------------------
%% compare to MATLAB find
tic % start timing of a matlab find
j = find(a > val, 1);
res2 = a(j);
toc % end timing of a matlab find
%// Benchmark
>> [res1, res2] = binarySearchExample(0.556)
Elapsed time is 0.000093 seconds.
Elapsed time is 0.327183 seconds.
res1 =
0.5560
res2 =
0.5560
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)