Index exceeds the number of array elements - Error message
1 次查看(过去 30 天)
显示 更早的评论
Posted a similar question before, but this time it is for taking an average of every 2 data points. For example: 1 2 is averaged, 3 4 is averaged, 5 6, 7 8, etc. I am getting an error where n1 is larger than the array, which is giving the error in ma. 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 10];
k = 1;
n1 = 1;
for n = 1:length(mdata)
ma(n) = (1/(k + 1)) * sum(mdata(n1:n1 + k));
n1 = (n1 + k) + 1;
std_ma(n) = std(ma);
end
Error message:
Index exceeds the number of array elements (10).
Error in untitled29 (line 9)
ma(n) = (1/(k + 1)) * sum(mdata(n1:n1 + k));
0 个评论
回答(2 个)
David Hill
2022-6-30
mdata = [1 2 3 4 5 6 7 8 9 10];
k = 1;
c = 1;
for n1 = 1:2:length(mdata)
ma(c) = (1/(k + 1)) * sum(mdata(n1:n1 + k));
std_ma(c) = std(ma);
c=c+1;
end
Steven Lord
2022-6-30
x = 1:10
y = reshape(x, 2, [])
m = mean(y, 1) % mean of each column; "collapse" dimension 1 to size 1 by taking the mean
m2 = mean(y, 2) % "collapse" dimension 2 to size 1 by taking the mean
All these assume that the number of elements in x is a multiple of 2. If it isn't the reshape call will error.
y2 = reshape([x, 11], 2, [])
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!