Evenly spaced numbers between two sets (Vectorize LINSPACE) - MATLAB

有些话、适合烂在心里 提交于 2019-12-13 12:29:02

问题


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


来源:https://stackoverflow.com/questions/29034188/evenly-spaced-numbers-between-two-sets-vectorize-linspace-matlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!