How to make vectors from two points vectors?

In one dimension, I could make a vector interpolates between two points by using ':' operator.
For example:
> index1 = 1;
> index2 = 10;
> vec = [index1:index2]
vec =
1 2 3 4 5 6 7 8 9 10
However, I can't make multiple vectors interpolated from the vector of two points.
What should I write in the following '???'.
> index1 = [1; 11, 21];
> index2 = [10; 20; 30];
> vecs = ??? % don't write: [index1(1):index2(1); index1(2):index2(2); index1(3):index2(3)]
vec =
1 2 3 4 5 6 7 8 9 10
11 12 13 14 15 16 17 18 19 20
21 22 23 24 25 26 27 28 29 30

 Accepted Answer

index1 = [1; 11; 21];
index2 = [10; 20; 30];
mat = cell2mat(arrayfun(@(x1,x2)x1:x2,index1,index2,'UniformOutput',false));

3 Comments

One could also make this a bit more generalized by doing
NC = 10;
mat = cell2mat(arrayfun(@(x1,x2)linspace(x1,x2,NC),index1,index2,'UniformOutput',false));
in case the rows do not have the same increments. This code would create 10 columns, regardless.
I guess it would depend on whether the data need to have a set interval or not but that does raise a caveat for my answer. If the paired values between index1 and index2 aren't at a fixed distance from each other my answer will result in a dimensions error. The error would be avoided in the cyclist's version but would not have fixed intervals.
% vv changed from 11 to 12
index1 = [1; 12; 21];
index2 = [10; 20; 30];
Thank you that worked great.

Sign in to comment.

More Answers (0)

Products

Release

R2018a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!