필터 지우기
필터 지우기

Getting error about index in for loop

조회 수: 2 (최근 30일)
Carly Hudson
Carly Hudson 2020년 5월 5일
댓글: per isakson 2020년 5월 5일
%for loop for plotting given data
for k = 0:size(dataN)
val = dataN(:,k);
avg = mean(val);
end
I am getting this error:
Index in position 2 is invalid. Array indices must be positive integers or logical values.
Error in Lab5_Problem2 (line 25)
val = dataN(:,k);
I cannot figure out why, but I am trying to extract the first row of the array (dataN). Thank you for any help!

답변 (1개)

per isakson
per isakson 2020년 5월 5일
편집: per isakson 2020년 5월 5일
Three problems:
  • replace 0:size(dataN) by 1:size(dataN,2). Matlab's indexing is one-based.
  • avg = mean(val); overwrites avg in every iteration; only the last value will persist
  • "trying to extract the first row of the array (dataN)" dataN(:,k) refers to the k:th column
  댓글 수: 2
Carly Hudson
Carly Hudson 2020년 5월 5일
How do I make it so avg is not overwritten every iteration? I think I am trying to refer to the kth coulmn because I am trying to extract the average from every column of data. Sorry if any of this is wrong, but I am very new to MatLab. Thank you for your help!
per isakson
per isakson 2020년 5월 5일
This should do it
wid = size(dataN,2);
avg = nan( 1, wid );
for k = 1 : wid
val = dataN(:,k);
avg(k) = mean(val);
end

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

카테고리

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

제품

Community Treasure Hunt

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

Start Hunting!

Translated by