필터 지우기
필터 지우기

Index exceeds the number of array elements - Error message

조회 수: 3 (최근 30일)
zen
zen 2022년 6월 30일
댓글: zen 2022년 7월 1일
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));

답변 (2개)

David Hill
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
std_ma = 1×5
0 1.4142 2.0000 2.5820 3.1623
  댓글 수: 1
zen
zen 2022년 7월 1일
What if I wanted to increase the averaging size from 2 to 3? I get the error again when I do that. for example:
mdata = [1 2 3 4 5 6 7 8 9 10];
k = 2;
c = 1;
for n1 = 1:3:length(mdata)
ma(c) = (1/(k + 1)) * sum(mdata(n1:n1 + k));
std_ma(c) = std(ma);
c = c + 1;
end
Index exceeds the number of array elements. Index must not exceed 10.

댓글을 달려면 로그인하십시오.


Steven Lord
Steven Lord 2022년 6월 30일
x = 1:10
x = 1×10
1 2 3 4 5 6 7 8 9 10
y = reshape(x, 2, [])
y = 2×5
1 3 5 7 9 2 4 6 8 10
m = mean(y, 1) % mean of each column; "collapse" dimension 1 to size 1 by taking the mean
m = 1×5
1.5000 3.5000 5.5000 7.5000 9.5000
m2 = mean(y, 2) % "collapse" dimension 2 to size 1 by taking the mean
m2 = 2×1
5 6
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, [])
Error using reshape
Product of known dimensions, 2, not divisible into total number of elements, 11.

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

제품


릴리스

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by