From: Loren Shure on
In article <hulehc$ecr$1(a)fred.mathworks.com>, priya.biomath(a)yahoo.co.in
says...
> I have a 2d matrix called A which has most of the element is zero and i want to find average of matrix
>
> I use
>
> Average = sum(nonzeros(A(:)))/numel(nonzeros(A(:)));
>
> Is it okey?
>
> It seems to me okey but problem is i choose maximum value in matrix A is 20 so the average should be also maximum 20.
>
> If one could undersatnd this then please help me to find error
> Because I am getting more than 20 for my average.
>

Shouldn't your mean account for having zeros as well? Why not

mean(A(:))?

--
Loren
http://blogs.mathworks.com/loren
http://matlabwiki.mathworks.com/MATLAB_FAQ
From: mat001 on
Loren Shure <loren.shure(a)mathworks.com> wrote in message <MPG.267829f6a173c605989af3(a)news.mathworks.com>...
> In article <hulehc$ecr$1(a)fred.mathworks.com>, priya.biomath(a)yahoo.co.in
> says...
> > I have a 2d matrix called A which has most of the element is zero and i want to find average of matrix
> >
> > I use
> >
> > Average = sum(nonzeros(A(:)))/numel(nonzeros(A(:)));
> >
> > Is it okey?
> >
> > It seems to me okey but problem is i choose maximum value in matrix A is 20 so the average should be also maximum 20.
> >
> > If one could undersatnd this then please help me to find error
> > Because I am getting more than 20 for my average.
> >
>
> Shouldn't your mean account for having zeros as well? Why not
>
> mean(A(:))?
>
> --
> Loren
> http://blogs.mathworks.com/loren
> http://matlabwiki.mathworks.com/MATLAB_FAQ

If i will consider those zeros then I will never get good average.
Because all the element are zero near all boundaries. only values are available in the middle

like

average of

0 0 0 5 5 5 0 0 0

will be 15/9

but i need average over nonzero
e.g
15/5
From: Jos (10584) on
"mat001 " <priya.biomath(a)yahoo.co.in> wrote in message <hulehc$ecr$1(a)fred.mathworks.com>...
> I have a 2d matrix called A which has most of the element is zero and i want to find average of matrix
>
> I use
>
> Average = sum(nonzeros(A(:)))/numel(nonzeros(A(:)));
>
> Is it okey?
>
> It seems to me okey but problem is i choose maximum value in matrix A is 20 so the average should be also maximum 20.
>
> If one could undersatnd this then please help me to find error
> Because I am getting more than 20 for my average.

Two improvements:

1) sum(nonzeros(A(:))) is, almost by definition of zero, the same as sum(A(:))
2) numel(nonzeros(A)) can be replaced by NNZ

Average = sum(A(:)) / nnz(A)

hth
Jos