多个起点和终点的高效冒号运算符 [英] Efficient colon operator for multiple start and end points

查看:29
本文介绍了多个起点和终点的高效冒号运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下两个变量:

Suppose I have the following two variables:

start_idx = [1 4 7];
end_idx   = [2 6 15];

我想高效(如果可能,不要循环)生成一行,其中包含在 start_idxend_idx 的相应元素之间应用的冒号运算符.对于此示例,这将导致:

I want to efficiently (no for loop if possible) generate a single row which consists of the colon operator being applied between corresponding elements of start_idx and end_idx. For this example, this would result in:

result = [1:2 4:6 7:15];

因此:

results = [1 2 4 5 6 7 8 9 10 11 12 13 14 15];

执行此操作的方法应该可以在 Simulink 的 MATLAB Function 模块中使用.非常感谢!

The method to do this should be usable inside Simulink's MATLAB Function block. Thank you very much!

推荐答案

这里是一种基于累积求和的矢量化方法 -

Here's a vectorized approach based on cumulative summation -

% Get lengths of each group
lens = end_idx - start_idx + 1;

% Determine positions in o/p array where groups would shift
shift_idx = cumsum(lens(1:end-1))+1

% Initialize ID array and at shifting positions place strategically created
% numbers, such that when ID array is cumulatively summed would result in
% desired "ramped" array
id_arr = ones(1,sum(lens));
id_arr([1 shift_idx]) = [start_idx(1) start_idx(2:end) - end_idx(1:end-1)];
out = cumsum(id_arr)

样品运行 -

start_idx =
     6     8    13
end_idx =
    11    11    15
out =
     6     7     8     9    10    11     8     9    10    11    13    14    15

这篇关于多个起点和终点的高效冒号运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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