Got Questions? Get Answers.
Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

Thread Subject:
non zero element in Matrix

Subject: non zero element in Matrix

From: mat001

Date: 17 May, 2010 12:22:04

Message: 1 of 5

How to find non zero element in Matrix

I have a matrix A with lots of Zero and I have to take average of only that element which is non zero.

Subject: non zero element in Matrix

From: mat001

Date: 17 May, 2010 12:27:04

Message: 2 of 5

"mat001 " <priya.biomath@yahoo.co.in> wrote in message <hsrcdc$i8m$1@fred.mathworks.com>...
> How to find non zero element in Matrix
>
> I have a matrix A with lots of Zero and I have to take average of only that element which is non zero.

Will it work like that

average = sum(nonzeros(A(:)))/numel(nonzeros(A(:)))

Subject: non zero element in Matrix

From: Sean

Date: 17 May, 2010 12:31:05

Message: 3 of 5

"mat001 " <priya.biomath@yahoo.co.in> wrote in message <hsrcdc$i8m$1@fred.mathworks.com>...
> How to find non zero element in Matrix
>
> I have a matrix A with lots of Zero and I have to take average of only that element which is non zero.

>>a = rand(10).*(rand(10)>.5);
>>b = a(a~=0);
>>mean(b)

or
>>a(a==0) = nan;
>>nanmean(a);

Subject: non zero element in Matrix

From: ImageAnalyst

Date: 17 May, 2010 12:31:23

Message: 4 of 5

It should work, but you can replace
numel(nonzeros(A(:)))
with
nnz(A)

Subject: non zero element in Matrix

From: Matt J

Date: 17 May, 2010 13:22:04

Message: 5 of 5

"mat001 " <priya.biomath@yahoo.co.in> wrote in message <hsrcmo$8is$1@fred.mathworks.com>...
> "mat001 " <priya.biomath@yahoo.co.in> wrote in message <hsrcdc$i8m$1@fred.mathworks.com>...
> > How to find non zero element in Matrix
> >
> > I have a matrix A with lots of Zero and I have to take average of only that element which is non zero.
>
> Will it work like that
>
> average = sum(nonzeros(A(:)))/numel(nonzeros(A(:)))

This can be replaced simply with

mean(nonzeros(A));

Tags for this Thread

No tags are associated with this thread.

What are tags?

A tag is like a keyword or category label associated with each thread. Tags make it easier for you to find threads of interest.

Anyone can tag a thread. Tags are public and visible to everyone.

Contact us