Index exceeds the number of array elements - Error message

1 visualizzazione (ultimi 30 giorni)
So I am getting an error where I believe n1 is larger than the array after n becomes n = 3, which is giving the error in ma. Premise of the code is to take 1 2, 3 4 5, 6 7 8 9, etc. Pretty sure I have to change the length but not sure how to go about it. What should I do? Here is the code:
clear all
mdata = [1 2 3 4 5 6 7 8 9];
n1 = 1;
k = 1;
for n = 1:length(mdata)
ma(n) = (1/(k + 1)) * sum(mdata(n1:n1 + k));
n1 = ((n1 + k) + 1);
k = k + 1;
std_ma = std(mdata);
end
Error message:
Index exceeds the number of array elements (9).
Error in untitled22 (line 11)
ma(n) = (1/(k + 1)) * sum(mdata(n1:n1 + k));

Risposta accettata

Voss
Voss il 28 Giu 2022
Here's one way to determine the number of iterations required:
clear all
mdata = [1 2 3 4 5 6 7 8 9];
n1 = 1;
k = 1;
N = numel(mdata);
n_iter = find(cumsum(2:N) <= N,1,'last')
n_iter = 3
for n = 1:n_iter
ma(n) = (1/(k + 1)) * sum(mdata(n1:n1 + k));
n1 = ((n1 + k) + 1);
k = k + 1;
std_ma = std(mdata);
end
disp(ma)
1.5000 4.0000 7.5000

Più risposte (0)

Prodotti


Release

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by