CaptainProg
CaptainProg

Reputation: 5690

Calculate mean of columns only

I have a function that calculates the mean of two columns of a matrix. For example, if the following matrix is the input:

inputMatrix =

                1   2   5   3   9
                4   6   2   3   2
                4   4   3   9   1

... And my command is:

outputVector = mean(inputArray(:,1:2))

...Then my output is:

outputVector = 

                3   4

The problem arises when my input matrix only contains one row (i.e. when it is a vector, not a matrix).

For example, the input:

inputMatrix =

               4   3   7   2   1

Gives the output:

outputVector = 

               3.5000

I would like the same behaviour to be maintained regardless of how many rows are in the input. To clarify, the correct output for the second example above should be:

outputVector =

               4   3

Upvotes: 5

Views: 26448

Answers (2)

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272497

mean(blah, 1)

See the documentation: http://www.mathworks.co.uk/help/techdoc/ref/mean.html.

Upvotes: 5

Jonas
Jonas

Reputation: 74940

Use the second argument of MEAN to indicate along which dimension you want to average

inputMatrix =[ 4   3   7   2   1]

mean(inputMatrix(:,1:2),1) %# average along dim 1, i.e. average all rows

ans =

     4     3

Upvotes: 13

Related Questions