Indexing error using sum
2 次查看（过去 30 天）
I have written a simple code that performs a moving average smoothing algorithm (it averages n adjacent bins to a single bin similar to Matlab's smooth):
signal = ones(1,30); % Random sample
n=3; % An odd number (filter span)
for i = k : length(signal)-k
NewSignal(i,:) = sum(signal(i-n:i+n,:))/n;
However, the second to last line results in the following error:
%Index in position 1 is invalid. Array indices must be positive integers or logical values.
So, what is the cause of this error? And what would be a solution?
Any explanation would be greatly appreciated.
KALYAN ACHARJYA 2019-5-19
编辑：KALYAN ACHARJYA 2019-5-19
%.......^ here is the issue
When you run the code n=3 initial and k=2;
When you assigned i=k:... that menas first value is 2
Which trsult >> signal(-1:5,:)
Negative and zero index value is not allowed. index value must be positive integer only as stated in error message-
Array indices must be positive integers or logical values. Soln: If you want to use the same expression >>Modify the initial value such a way that k>n, ensure that k value is integer.
Learn array indexing here