Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

Vectorizing the Notion of Colon (:) - values between two vectors in MATLAB

I have two vectors, idx1 and idx2, and I want to obtain the values between them. If idx1 and idx2 were numbers and not vectors, I could do that the following way:

idx1=1;
idx2=5;
values=idx1:idx2 

% Result
 % values =
 % 
 %    1     2     3     4     5

But in my case, idx1 and idx2 are vectors of variable length. For example, for length=2:

idx1=[5,9];
idx2=[9 11];

Can I use the colon operator to directly obtain the values in between? This is, something similar to the following:

values = [5     6     7     8     9     9    10    11]

I know I can do idx1(1):idx2(1) and idx1(2):idx2(2), this is, extract the values for each column separately, so if there is no other solution, I can do this with a for-loop, but maybe Matlab can do this more easily.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Your sample output is not legal. A matrix cannot have rows of different length. What you can do is create a cell array using arrayfun:

values = arrayfun(@colon, idx1, idx2, 'Uniform', false)

To convert the resulting cell array into a vector, you can use cell2mat:

values = cell2mat(values);

Alternatively, if all vectors in the resulting cell array have the same length, you can construct an output matrix as follows:

values = vertcat(values{:});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...