首页 > 解决方案 > 查找二进制向量中第 n 次出现 1 的索引(matlab)

问题描述

我有一个像这样的二进制向量x = [0 0 1 1 1 1 1 1 1]。我想找到让我们说第 7 个 1 的索引,即 9。

我知道我可以这样做:

y = find(x);
index = y(7);

但是如果向量很大并且我想节省内存使用量怎么办?不会y = find(x)占用大量内存吗?如果是这样,有没有办法解决这个问题?

我将其用作在线性规划问题中存储非基元素和基元素的索引的替代方法。所以我想避免将索引存储为数值。

以下是一个很好的解决方案吗?

basis = [0 0 1 1 1 1 1 1 1];
basisIndex = 7;
correctIndex = getIndex(basisIndex, basis); % should be 9 when basisIndex = 7

function ret = getIndex(basisIndex, basis) 
    counter = 1;
    for value = find(basis) % iterate through [3, 4, 5, 6, 7, 8, 9]
        if counter == basisIndex
            ret = value;
            break;
        end
        counter = counter + 1;
    end
end

标签: matlabvectorindexingbinary

解决方案


只需遍历x. 首先,它不会创建新的向量y=find(x)(节省内存)。其次,如果basisIndex小,效率会更高。

假设x是一个 1e8 x 1 的向量。让我们find与仅迭代进行比较。

basis = randi(2,1e8,1) - 1;
basisIndex = 7;

tic % your first method
y = find(basis);
index = y(basisIndex);
toc

tic % iterate through base
index = 1;
match = 0;
while true
    if basis(index)
        match = match + 1;
        if match == basisIndex
            break
        end
    end
    index = index + 1;     
end 
toc

输出

Elapsed time is 1.214597 seconds.
Elapsed time is 0.000061 seconds.

即使basisIndex很大

basisIndex = 5e7;

迭代的结果仍然更有效

Elapsed time is 1.250430 seconds. % use find
Elapsed time is 0.757767 seconds. % use iteration

推荐阅读