필터 지우기
필터 지우기

Index exceeds the number of array elements - Error message

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

채택된 답변

Voss
Voss 2022년 6월 28일
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
zen
zen 2022년 6월 30일
Thank you so much, it worked!
Voss
Voss 2022년 6월 30일
You're welcome!

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

추가 답변 (0개)

카테고리

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