【问题标题】:Find index of nth occurence of 1 in binary vector (matlab)查找二进制向量中第 n 次出现 1 的索引(matlab)
【发布时间】:2019-04-13 17:25:21
【问题描述】:

我有一个像 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

【问题讨论】:

  • 我在问题的最后添加了一些信息。我在想保存 find 返回的值会带走将索引存储在二进制向量中的优势。
  • @SardarUsama 我在想我添加的功能会节省内存?

标签: matlab vector indexing binary


【解决方案1】:

只需遍历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

【讨论】:

    猜你喜欢
    • 2018-06-20
    • 1970-01-01
    • 2016-11-21
    • 1970-01-01
    • 1970-01-01
    • 2015-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多