repeating a vector with increments

1 次查看(过去 30 天)
Jeong Ho
Jeong Ho 2015-2-20
回答: arich82 2015-2-20
Dear Matlab Central users, Hi, I have a row vector I and I want to create a row vector [I I+n I+2*n ... I+(N-1)*n] where N>1 and n are positive integers. For example, if I = [2 3] and N = n = 3, [2 3 5 6 6 9] Is there a trick to doing this efficiently? Thank you all!
Best, John

回答(2 个)

Star Strider
Star Strider 2015-2-20
The output vector you listed does not seem to me to correspond to the rule for it you posted. Please clarify.
This otherwise seems to work:
N = 3;
I = [2 3];
Q = (cumsum(ones(N,2))-1)*N;
Ym = bsxfun(@plus, I, Q);
Yv = reshape(Ym', 1, []); % Output
produces:
Yv =
2 3 5 6 8 9

arich82
arich82 2015-2-20
Assuming you have a typo in your example and your desired output is actually
[2, 3, 5, 8, 9]
(i.e. an 8 instead of the repeated 6), then I think this should do what you want:
n = 3;
N = 3;
a = [2, 3];
b = n*[0:N-1];
c = bsxfun(@plus, a.', b);
c = c(:).'
or as a messy one-liner:
reshape(bsxfun(@plus, [2, 3].', 3*(0:3-1)), 1, []);
No gurantees that someone won't have a more clever solution, but if this doesn't give the desired result, perhaps a little more clarification would be helpful.

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by