Evenly spaced numbers between two sets (Vectorize

2019-05-13 17:21发布

问题:

How can I define a matrix M according to M=[a:(b-a)/5:b] (from a to b in 5 steps), when a and b are vectors or sets; more specifically, each row i in M should have a first value equal to a(i) and last value b(i) and, in between, 5 equal steps.

For example, if I have

a = [0;     b = [10;
     0];         20]; 

I'd like to produce a matrix M of the form

[0 2 4  6  8 10;...
 0 4 8 12 16 20]

I know how to do this using loops, but I'm looking for a solution without. How can I do that?

回答1:

One vectorized approach with bsxfun -

steps = 5                               %// number of steps
M = bsxfun(@plus,((b(:)-a(:))./(steps-1))*[0:steps-1],a(:))

Sample run -

a =
     2
     3
b =
    18
    23
M =
     2     6    10    14    18
     3     8    13    18    23


回答2:

Here is a way using arrayfun (slower than @Divakar's bsxfun solution) but just for the sake of it:

clear
clc

a=[0;0];
b=[10;20];

%// Customize the stepsize
Step = 5;

M = cell2mat(arrayfun(@(a,b) (a:(b-a)/Step:b), a,b,'uni',false))

M =

     0     2     4     6     8    10
     0     4     8    12    16    20