MATLAB基于长度向量的重复数字 [英] MATLAB repeat numbers based on a vector of lengths

查看:126
本文介绍了MATLAB基于长度向量的重复数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否存在矢量化方法来执行以下操作? (以示例显示):

Is there a vectorised way to do the following? (shown by an example):

input_lengths = [ 1 1 1 4       3     2   1 ]
result =        [ 1 2 3 4 4 4 4 5 5 5 6 6 7 ]

我已经将input_lengths隔开了,所以很容易理解如何获得结果

I have spaced out the input_lengths so it is easy to understand how the result is obtained

所得向量的长度为:sum(lengths).我目前使用以下循环计算result:

The resultant vector is of length: sum(lengths). I currently calculate result using the following loop:

result = ones(1, sum(input_lengths ));
counter = 1;
for i = 1:length(input_lengths)
    start_index = counter;
    end_index = counter + input_lengths (i) - 1;

    result(start_index:end_index) = i;
    counter = end_index + 1;
end

我也可以使用arrayfun来做到这一点(尽管这不完全是矢量化函数)

I can also do this using arrayfun (although that is not exactly a vectorised function)

cell_result = arrayfun(@(x) repmat(x, 1, input_lengths(x)), 1:length(input_lengths), 'UniformOutput', false);
cell_result : {[1], [2], [3], [4 4 4 4], [5 5 5], [6 6], [7]}

result = [cell_result{:}];
result : [ 1 2 3 4 4 4 4 5 5 5 6 6 7 ]

推荐答案

result = zeros(1,sum(input_lengths));
result(cumsum([1 input_lengths(1:end-1)])) = 1;
result = cumsum(result);

这应该很快.而且内存使用量是最小的.

This should be pretty fast. And memory usage is the minimum possible.

由于Bentoy13而产生的上述代码的优化版本(请参见他的非常详细的基准测试):

An optimized version of the above code, due to Bentoy13 (see his very detailed benchmarking):

result = zeros(1,sum(input_lengths));
result(1) = 1;
result(1+cumsum(input_lengths(1:end-1))) = 1;
result = cumsum(result);

这篇关于MATLAB基于长度向量的重复数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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