matlab - 多个起点和终点的高效冒号运算符

标签 matlab vectorization simulink

假设我有以下两个变量:

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

我想有效地(如果可能的话没有for循环)生成一个单行,其中包含在start_idxend_idx的相应元素之间应用的冒号运算符。对于此示例,这将导致:

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 block 中使用。非常感谢!

最佳答案

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

% 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)

sample 运行-

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

关于matlab - 多个起点和终点的高效冒号运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38501128/

相关文章:

python - 如何通过应用 numpy 向量化使用条件检查从 python 列表或 numpy 数组中提取值?

linux - 如何在Windows下使用Matlab嵌入式编码器为LINUX编译?

matlab - 确定无需编译/执行的直接馈通路径

performance - 如何在 Octave 中对方法进行基准测试?

matlab - 在 Matlab 中的函数之间共享 "many"变量

matlab - 如何在MATLAB中很好地向量化以下关于向量的偏导数?

c - PADDD 指令的操作数

c - 这种技术会减少 MATLAB 实时研讨会编码器的编译时间吗?

python - Matplotlib 类似于 matlab trisurf

matlab - 在 MATLAB 中使用 plot3 绘制圆锥体