matlab - 查找二进制向量中第 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
解决方案
只需遍历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
推荐阅读
- reactjs - 调用 redux 操作的相应组件未捕获 Redux 响应
- elasticsearch - 使用弹性应用搜索实现基于标签的搜索
- c - 在我的情况下,C 语言中的“无符号”字是什么?
- laravel - 如何将以下查询转换为 Eloquent?
- swift - Swift 5.5:逐行异步迭代文件
- gmail - Gmail:帐户在发送时被禁用。您的消息未发送
- laravel - 如何使用 Laravel 7+ 在文件中记录 Guzzle Http 请求响应
- firebase - 我们有没有办法将角色设置为手动添加用户 firebase 控制台?
- elasticsearch - AWS ElasticSearch - Kibana 仪表板未加载
- java - Socket 无法连接到 ServerSocket 中指定的 IP 地址。(安卓工作室)