trying to make a new array that is the sum of the previous entry for an unknown length
조회 수: 33 (최근 30일)
이전 댓글 표시
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
채택된 답변
Voss
2024년 12월 3일 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)
추가 답변 (0개)
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!