how to identify number of values in a column vector that are not zero values and are not NaN values?

Hello,
Lets say I have a 2458 x 1 column vector in a cell array, A, that contains zeros, nonzeros, and NaN values. I would like to identify how many values are nonzero values and are not NaN values. This means that I have to filter out the zero values and NaN values. This is the current code I'm using but this portion, (A{1,1} ~= NaN), seems to not be working.
logical = (A{1,1} ~= 0) & (A{1,1} ~= NaN);
A{1,1}(~logical) = [];
length(A{1,1})
When I run the code, it has a 1 value at the row indices that contain NaN, meaning that the row index value is true...But it shouldn't be because it is a NaN value and I want to only determine the values that are nonzero and are not NaN values. I was wondering why this does not work and what I can do to fix this? I'm using 2015a btw and any help or advice would be appreciated.

 Accepted Answer

I don’t have your cell array to experiment with, but this works for my synthesised one:
A = {1, 3, 5, NaN, 7, 11, 13, 0 17};
logc = @(x) (x ~= 0) & ~isnan(x);
Idx = cellfun(logc, A);

4 Comments

Hello again Star Strider, thanks for your quick response.
So once the logical array is outputted, how would you go about determining the number of ones in the logical array? I would do something like this:
length(find(logc == 1))
or
A(~logc = [])
length(A)
Or do you prefer another method?
My pleasure.
To determine the number of ones in the vector, the sum or nnz functions will both work:
NonZeroEmenents = sum(Idx);
NonZeroElements = nnz(Idx);
You have to use the ‘Idx’ vector, not the ‘logc’ function.
Never knew about nnz function, which is pretty neat. And summing the vector is another great idea. I'm glad I asked you that question even though I already had other feasible solutions as stated in my first comment. Thanks again!

Sign in to comment.

More Answers (0)

Categories

Community Treasure Hunt

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

Start Hunting!