Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
575 views
in Technique[技术] by (71.8m points)

matlab - Efficient colon operator for multiple start and end points

Suppose I have the following two variables:

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

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];

Therefore:

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)

Sample run -

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...