trying to make a new array that is the sum of the previous entry for an unknown length
33 views (last 30 days)
Show older comments
I am writing a code that adds the length of a previous element of an array into a new array with an unknown length but am having problems. Hypothetically, say i have an array of [1 2 3 4], I want the new array I am creating to be [1, 3, 6, 10]. In this code history is my array I have already found and i am trying to save the new array into playVal. I am currently getting the error message "Array indices must be positive integers or logical values," and I am too inexperienced with coding to be able to think up a solution.
n = length(history);
count = 1;
playVal = [];
while length(playVal) <= n
playVal(end+1) = history(count) + history(count - 1);
count = count + 1;
end
Accepted Answer
Voss
on 3 Dec 2024 at 19:14
history = [1 2 3 4];
One way:
n = length(history);
playVal = zeros(1,n);
if n > 0
playVal(1) = history(1);
for count = 2:n
playVal(count) = history(count) + playVal(count-1);
end
end
playVal
A simpler alternative:
playVal = cumsum(history)
2 Comments
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!