Index exceeds the number of array elements - Error message
조회 수: 3 (최근 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!