Most efficient way to generate an array around a central value

17 ビュー (過去 30 日間)
De Ar
De Ar 2018 年 7 月 19 日
編集済み: Jan 2018 年 7 月 19 日
Hi!
I am trying to span a linearly spaced array around a center value without knowing number of points in the array beforehand. I only have the step size and the lower and upper limits that must not be exceeded. For example, if center = -4,3, stepsize = 2, lower = -7, upper = 3, then the resulting array should be array = [-6.3 -4.3 -2.3 -0.3 1.7].
Is there a way to generate such an array as efficiently as possible (e.g. without while-loops)?
Thanks for all the help in advance!

採用された回答

Jan
Jan 2018 年 7 月 19 日
編集済み: Jan 2018 年 7 月 19 日
A bold guess:
center = -4.3
step = 2
low = -7
high = 3
vhigh = center:step:high;
vlow = center - step:-step:low;
result = [vlow(end:-1:1), vhigh]
Or in one step:
L = low + rem(center - low, step);
H = high - rem(high - center, step);
result = L:step:H
I'm not sure if this is more stable considering rounding errors:
result = linspace(L, H, 1 + (H-L) / step)

その他の回答 (1 件)

Adam
Adam 2018 年 7 月 19 日
編集済み: Adam 2018 年 7 月 19 日
[ flip( center:-stepsize:lower ), ( center + stepsize ):stepsize:upper ];
looks like it would work, though I haven't tested all edge cases and there are probably neater ways.
If you prefer you could just do the simpler:
unique( [ flip( center:-stepsize:lower ), center:stepsize:upper ] );
to get rid of the duplicated centre point, though I imagine it is less efficient.

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by