Bug with mean() on floating point vector elements

Can someone explain this bug?
a = rand(100,1);
mean(a(4), a(6))
Output:
Error using sum
Dimension argument must be a positive integer scalar within indexing range.
Error in mean (line 117)
y = sum(x, dim, flag)/size(x,dim);

1 Kommentar

Stephen23
Stephen23 am 13 Dez. 2017
"Can someone explain this bug?"
What bug? The fact that you are using mean in a way that is not supported by MATLAB just means that you need to read the documentation.

Melden Sie sich an, um zu kommentieren.

 Akzeptierte Antwort

Jan
Jan am 13 Dez. 2017
Bearbeitet: Jan am 13 Dez. 2017

0 Stimmen

This is not a bug. Please read the documentation, if you have a problem with a command:
doc mean
The 2nd argument of mean must be the dimension to operate on. Then a floating point number between 0 and 1 will not work. See:
a = magic(3)
mean(a, 1)
mean(a, 2)
You forgot to mention, what you want to calculate. Maybe you mean:
a = rand(100, 1);
mean(a([4,6]))
% or
mean(a(4:6))

3 Kommentare

Victor
Victor am 13 Dez. 2017
Bearbeitet: Victor am 13 Dez. 2017
OK, then why this code doesn't throw the same error: a = [3,5,2,5,3]'; mean(a(3), a(4))
Understood - it tries to calculate along singleton dimension.
Looking at your a vector, what is a(4)? It's 5. Can you take the mean of a two-dimensional array in the fifth dimension? Sure. While a(3) doesn't look like it has a fifth dimension, if you ask for the size of a(3) in the fifth dimension what does MATLAB return?
size(a(3), 5) % returns 1
See this Answer for some discussion of trailing singleton dimensions.
The reason your original attempt didn't work is that arrays in MATLAB don't have (for example) a 0.25th dimension.
Stephen23
Stephen23 am 13 Dez. 2017
@Viktor: it does not try to calculate along the singleton dimension, it actually does calculate along the singleton dimension.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Gefragt:

am 13 Dez. 2017

Kommentiert:

am 13 Dez. 2017

Community Treasure Hunt

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

Start Hunting!

Translated by