简体   繁体   English

索引超过了 MATLAB 中的数组元素数 (9)

[英]Index exceeds the number of array elements (9) in MATLAB

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.所以我收到一个错误,我认为 n1 在 n 变为 n = 3 后大于数组,这在 ma 中给出了错误。 Premise of the code is to take 1 2, 3 4 5, 6 7 8 9, etc. and average each group.代码的前提是取1 2, 3 4 5, 6 7 8 9 等,对每组取平均值。 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).索引超过数组元素的数量 (9)。

Error in untitled22 (line 11) ma(n) = (1/(k + 1)) * sum(mdata(n1:n1 + k)); untitled22 中的错误(第 11 行)ma(n) = (1/(k + 1)) * sum(mdata(n1:n1 + k));

The issue is that you are replacing the value of n1 with n1+k+1 on each step through the loop.问题是您在循环的每一步都将 n1 的值替换为n1 n1+k+1 At the start of the 4th iteration, n1=10 and k=4 , meaning you are trying to take the sum of elements 10:14 but the array only has 9 elements.在第 4 次迭代开始时, n1=10k=4 ,这意味着您尝试将元素的总和设为 10:14 但数组只有 9 个元素。

It is not clear from your question exactly what averages you are trying to calculate through all of the iterations of the loop and so it is difficulty to say more.从您的问题中不清楚您正在尝试通过循环的所有迭代计算什么平均值,因此很难说更多。 But, most likely, you do not need to manually calculate the average yourself.但是,您很可能不需要自己手动计算平均值。 Just define the subset of the data you want to work with on that iteration and take the mean of that.只需定义要在该迭代中使用的数据子集并取其平均值即可。

I am also guessing that you want to modify the assignment of std_ma at the end of your loop to only perform the std on the subset of data you are working with.我还猜测您想在循环结束时修改 std_ma 的分配,以便仅对您正在使用的数据子集执行 std。 Currently you are doing the calculation over all values in mdata and repeating that same calculation 9 times.目前,您正在计算mdata中的所有值并重复相同的计算 9 次。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM