trying to make a new array that is the sum of the previous entry for an unknown length
32 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Jacob
el 3 de Dic. de 2024 a las 18:51
Comentada: Voss
el 3 de Dic. de 2024 a las 19: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
Respuesta aceptada
Voss
el 3 de Dic. de 2024 a las 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 comentarios
Más respuestas (0)
Ver también
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!