Matlab索引到逻辑索引 [英] Matlab index to logic indexing

查看:181
本文介绍了Matlab索引到逻辑索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我给出了一个索引列表,例如i = [3 5]和向量v = 1:6.我需要一个函数f,该函数在给定索引i的情况下返回向量v的逻辑映射,例如:

I have given a list of indices, e.g. i = [3 5] and a vector v = 1:6. I need a function f which returns the logical map for the vector v given the indices i, e.g.:

f(i, length(v)) = [0 0 1 0 1 0]

由于我将调用此函数数百万次,因此我希望使其尽快运行.是否有执行该任务的内置函数?

Since I will call this function several million times, I would like to make it as fast as possible. Is there a builtin function which performs this task?

推荐答案

我知道我迟到了,但是我真的很想找到一个更快的解决方案,它与ismember一样优雅.确实有一种使用未公开的 ismembc 函数:

I know I'm late in the game, but I really wanted to find a faster solution which is just as elegant as ismember. And indeed there is one, that employs the undocumented ismembc function:

ismembc(v, i)

基准

N = 7;
i = [3 5];

%// slayton's solution
tic
for ii = 1:1e5
    clear idx;
    idx(N) = false;
    idx(i) = true;
end
toc

%// H.Muster's solution
tic
for ii = 1:1e5
    v = 1:N;
    idx = ismember(v, i);
end
toc

%// Jonas' solution
tic
for ii = 1:1e5
    idx = sparse(i, 1, true, N, 1);
end
toc

%// ismembc solution
tic
for ii = 1:1e5
    v = 1:N;
    idx = ismembc(v, i);
end
toc

这就是我得到的:

Elapsed time is 1.482971 seconds.
Elapsed time is 6.369626 seconds.
Elapsed time is 2.039481 seconds.
Elapsed time is 0.776234 seconds.

令人惊讶的是,ismembc确实是最快的!

Amazingly, ismembc is indeed the fastest!


对于非常大的N值(即,当v是大数组时),更快的解决方案实际上是slayton(和HebeleHododo).您有多种策略可供选择,请仔细选择:)


For very large values of N (i.e. when v is a large array), the faster solution is actually slayton's (and HebeleHododo's, for that matter). You have quite a variety of strategies to choose from, pick carefully :)

H.Muster
以下是基准测试结果,包括_ismemberoneoutput:

Edit by H.Muster:
Here's are benchmark results including _ismemberoneoutput:

Slayton's solution:
   Elapsed time is 1.075650 seconds.
ismember:
   Elapsed time is 3.163412 seconds.
ismembc:
   Elapsed time is 0.390953 seconds.
_ismemberoneoutput:
   Elapsed time is 0.477098 seconds.

有趣的是,乔纳斯(Jonas)的解决方案并没有为我运行,因为出现了Index exceeds matrix dimensions.错误...

Interestingly, Jonas' solution does not run for me, as I get an Index exceeds matrix dimensions. error...

通过hoogamaphone
值得注意的是,ismembc要求两个输入均为数字,排序,非稀疏,非NaN值,这是一个很容易在

Edit by hoogamaphone:
It's worth noting that ismembc requires both inputs to be numerical, sorted, non-sparse, non-NaN values, which is a detail that could be easily missed in the source documentation.

这篇关于Matlab索引到逻辑索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆