How to create an array of the form [1,2,4,7,11,16] without the use of a loop?
2 views (last 30 days)
Show older comments
Is is possible to create a Matlab array where the jump between two consecutive numbers is not constant but increases by 1 every time?
0 Comments
Accepted Answer
Star Strider
on 2 Aug 2015
It is, using the cumsum function (and a bit of fudging to get the result you want):
x = 1:5;
xs = [1 1+cumsum(x)]
xs =
1 2 4 7 11 16
3 Comments
Star Strider
on 2 Aug 2015
My pleasure!
A more efficient approach (that I was just going to post) is:
x = 0:5;
xs = 1+cumsum(x)
giving the same result.
Image Analyst
on 2 Aug 2015
To make it a little more general, you can do this:
numElements = 5;
startingValue = 10;
x = 0:(numElements-1);
xs = startingValue + cumsum(x)
Or if cumsum() is a little hard to follow or understand, you can use a for loop:
% Define parameters
startingValue = 10;
numElements = 5;
% Now construct an array that has a first value of startingValue
% and has numElements total number of elements,
% where each element increases by 1, 2, 3, 4, ...
% from the element before it.
x = startingValue % Initialize first element.
for k = 2 : numElements
x(k) = x(k-1) + (k-1);
end
% Show in command window.
x
More Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!