简体   繁体   中英

How to compute a mean of a specific column of a matrix, excluding a given value IN MATLAB

I have a 1000x7 matrix whose columns present some values equal to -99 .

I want to compute the mean of each column separately because I'm building a table using fprintf , but I want the mean to be computed excluding the -99 values.

For instance, taking matrix A , I've tried

mean(A(A(:,1) ~= -99))

and it works for the computation of the first column mean.

However, when I try

mean(A(A(:,2) ~= -99))

for the second column, the result is exactly equal to the result of the first column.

What's wrong in that? Thanks a lot in advance for your tips!

You are taking the index values to first column only.

Try

mean(A(A(:,2) ~= -99),2) %for 2nd column

In short: You need to specify the column when reading the values:

mean(A(A(:,2) ~= -99, 2))

A longer version: A(:,1) ~= -99 returns an 1000 x 1 logical array, so does A(:,2) ~= -99 . When indexing with logical arrays Matlab effectively flattens both arrays, and extracts the values for which the logical array is true .

If the logical array B has M elements and the array that is being indexed into, A , has N elements where M <= N Matlab will only operate on the first M elements of B ie C = A(B) would be equivalent to*

C = A(1:M);
C = C(B);

In your example you are indexing into a 1000 x 7 array with a 1000 x 1 logical array, which makes all calls only consider the first 1000 elements, ie the first column. You therefore need to specify which column(s) you want the logical index to apply to.

*If B is an 1xM array the resulting array will also be reshaped into an 1xM array, for all other cases an Mx1 array is returned.

What you need is, for say, the first column:

mean(A(find(A(:,1) ~= -99),1))

For example:

>> A

A =

     1     2
     1     3
   -99     4
     1     5

Then,

>> find(A(:,1)~=-99)

ans =

     1
     2
     4

And,

>> mean(A(find(A(:,1)~=-99),1))

ans =

     1

You are using a vector, A(:,1)~=-99 , to index into an array so it's only accessing values in the first column. Here's an example of how you can do this calculation for each column in your array:

A = [1 2 3; -99, 4, 3; 10 4 8];

for col = 1:3
    index = A(:,col) ~= -99;
    mean(A(index,col))
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM