user3177755
user3177755

Reputation: 27

How to calculate average with taking into account only certain values

I'm working with a large matrix that contains a lot of zero values.When I transform this matrix from a list table to a cross table, I have more zero values in it.I want to keep all the initial values in it and and supress all the zero values added from matlab for the calculation of the average.Here is an example of what I want to do:

x=

0.6000    0.6000    5.0000

0.6000    0.8000    6.0000

0.6000    0.8500         0

0.6000    0.8200         0

0.8000    0.8000    9.0000

0.8000    0.9000    2.0000

List table to cross table

   NaN    0.6000    0.8000    0.8200    0.8500    0.9000
0.6000    5.0000    6.0000         0         0         0 Average=(5+6+0+0)/4=2,75
0.8000         0    9.0000         0         0    2.0000 Average=(9+2)/2=5,5

Thanks in advance

Upvotes: 0

Views: 113

Answers (3)

Dennis Jaheruddin
Dennis Jaheruddin

Reputation: 21563

Here are some descriptions that should not be hard to follow. Pick the one that matches your needs.

Assuming that you want to take the average of combinations that contain at least 1 record, I suppose you need more information than just the resulting table.

Either you need to keep an index of which values occur, or you need to look it up in the source table. Alternately, you can also just initialize the table with NaN values and only put values there if the combination occurs in the original list.


An alternate approach would just be to add a count to the original list, of how often each value occurs and then do the calculations based on that.

Upvotes: 0

Divakar
Divakar

Reputation: 221574

If you are looking to find the mean of a matrix without considering the zeros, try this -

%%// Given matrix
x =   [NaN    0.6000    0.8000    0.8200    0.8500    0.9000;
0.6000    5.0000    6.0000         0         0         0;
0.8000         0    9.0000         0         0    2.0000] 

x1 = x;
x1(x==0)=NaN;
rowwise_mean_without_zeros = nanmean(x1,2) %%// mean of rows
whole_mean_without_zeros = nanmean(x1(:)) %%// mean of the whole matrix

Output

rowwise_mean_without_zeros =

    0.7940
    3.8667
    3.9333


whole_mean_without_zeros =

    2.4882

Upvotes: 1

Luis Mendo
Luis Mendo

Reputation: 112679

To compute the mean excluding the zeros you can use

result = sum(x(:))/nnz(x);

To compute the mean of each row excluding the zeros:

result = sum(x.')./sum(x.'~=0);

The above solutions assume all zeros should be removed from the computations.

Upvotes: 2

Related Questions