how calculate percentage with a vector and a matrix with nan elements?

1 view (last 30 days)
I have a vector V where each element of V is bigger than zero, and a matrix M where each row represent data, each column the source of the data, and each element the number of errors.
A small example will be:
V=[10 5 4 8];
M=[0 2 NaN 4 ;
0 0 3 2 ;
0 NaN 0 1 ;
0 2 NaN 0 ];
I would like to calculate a vector P with the percentage or error without for loops and without consider the part of the matrix with NaN elements such as
P=[((0+0+0+0)/(10+5+4+8))*100 ((2+0+2)/(10+5+8))*100 ((3+0)/(5+4))*100 ((4+2+1+0)/(10+5+4+8))*100]
P=[ 0 17.3913 33.3333 25.9259]

Accepted Answer

dpb
dpb on 3 Aug 2016
Edited: dpb on 3 Aug 2016
>> m=M;m(isnan(m))=0;
>> sum(m)./sum(repmat(V.',1,size(M,2)).*isfinite(M))*100
ans =
0 17.3913 33.3333 25.9259
>>
If you don't need M any longer, can do the substitution in place, of course. It'd be nice if were syntax with M(isfinite(M)) could return an array with a filler value for the missing locations as an alternate syntax to needing the temporary variable.
ADDENDUM
Oh, forgotted about nansum; it's in Statistics Toolbox in R2012b; not sure if got propagated to base product later or not; seems like maybe??? With it, can get rid of explicit temporary step...
nansum(M)./sum(repmat(V.',1,size(M,2)).*isfinite(M))*100

More Answers (0)

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!