How do I take the average of a zeros vector without dividing by the unpopulated zeros?

I am using real time data coming in and it is being populated into a matrix of zeros. I have the current code...
handles.vxdata= zeros(2400)
handles.speedmax= max(handles.vxdata)
%This works perfect b/c it just picks the max value out of the zeros vector
handles.speedavg=mean(handles.vxdata)
%I am having trouble with this command because it is taking my matrix of zeros and dividing by all the values in the vector, including the zeros that have not been populated with real time data.
I am looking to create a command that only uses the data in the matrix that has values.

 採用された回答

Matt Kindig
Matt Kindig 2013 年 3 月 12 日
So basically you just want to exclude zeros from your mean?
notZero = (handles.vxdata)~=0;
handles.speedavg = mean(handles.vxdata(notZero));

1 件のコメント

Matt Kindig
Matt Kindig 2013 年 3 月 12 日
I might suggest, though, if handles.vxdata is a double matrix, to pre-allocate handles.vxdata using NaN's, not zeros. That way, if you have a "real" value that is identically zero, it is distinct from your preallocated value.
Also, zeros(2400) will make a 2400x2400 matrix, not a 2400x1 matrix. Is this what you want?

サインインしてコメントする。

その他の回答 (1 件)

Walter Roberson
Walter Roberson 2013 年 3 月 12 日
If you are using a vector instead of a matrix, then
handles.speedavg = mean(nonzeros(handles.vxdata));

カテゴリ

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by