Index exceeds the number of array elements - Error message

1 Ansicht (letzte 30 Tage)
zen
zen am 30 Jun. 2022
Kommentiert: zen am 1 Jul. 2022
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));

Antworten (2)

David Hill
David Hill am 30 Jun. 2022
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 Kommentar
zen
zen am 1 Jul. 2022
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.

Melden Sie sich an, um zu kommentieren.


Steven Lord
Steven Lord am 30 Jun. 2022
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.

Kategorien

Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange

Produkte


Version

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by