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

spa*_*ger 6 matlab simulink vectorization

假设我有以下两个变量:

start_idx = [1 4 7];
end_idx   = [2 6 15];
Run Code Online (Sandbox Code Playgroud)

我想有效地(无for循环如果可能的话)产生的单排它由操作者结肠中的相应元件之间施加start_idxend_idx.对于此示例,这将导致:

result = [1:2 4:6 7:15];
Run Code Online (Sandbox Code Playgroud)

因此:

results = [1 2 4 5 6 7 8 9 10 11 12 13 14 15];
Run Code Online (Sandbox Code Playgroud)

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

Div*_*kar 5

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

% 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)
Run Code Online (Sandbox Code Playgroud)

样品运行-

start_idx =
     6     8    13
end_idx =
    11    11    15
out =
     6     7     8     9    10    11     8     9    10    11    13    14    15
Run Code Online (Sandbox Code Playgroud)


Bil*_*eey 2

正如我在评论中指出的,解决这个问题的一个方法是:

out=cell2mat(arrayfun(@(x,y)[x:y],start_idx,end_idx,'uniformoutput',false));
Run Code Online (Sandbox Code Playgroud)

arrayfun调用将创建一个元胞数组,其每个元胞都是输出的一部分:

ans =

     1     2


ans =

     4     5     6


ans =

  Columns 1 through 8

     7     8     9    10    11    12    13    14

  Column 9

    15
Run Code Online (Sandbox Code Playgroud)

通过将其包装在调用中,cell2mat您可以获得预期的输出:

out =

  Columns 1 through 8

     1     2     4     5     6     7     8     9

  Columns 9 through 14

    10    11    12    13    14    15
Run Code Online (Sandbox Code Playgroud)