Index exceeds the number of array elements - Error message

1 vue (au cours des 30 derniers jours)
zen
zen le 28 Juin 2022
Commenté : Voss le 30 Juin 2022
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));

Réponse acceptée

Voss
Voss le 28 Juin 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
  2 commentaires
zen
zen le 30 Juin 2022
Thank you so much, it worked!
Voss
Voss le 30 Juin 2022
You're welcome!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Matrix Indexing dans Help Center et File Exchange

Produits


Version

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by