1

I need to find out the amount of non-zero elements with Matlab hashmap/hash-tables, nnz does not work with it. For example, nnz(hhh.values) does not work. How can I check non-zero elements in Matlab's hashmap?

keys = {'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'};
values = {327.2, 368.2, 197.6, 178.4, 100.0,  69.9}
hhh = containers.Map(keys, values)
nnz(hhh.values)

returns

Undefined function 'nnz' for input arguments of type 'cell'.

Community
  • 1
  • 1
hhh
  • 50,788
  • 62
  • 179
  • 282

1 Answers1

2

Well, it's a bit ugly, but if you want something compact you can use cellfun in conduction with nnz:

nnz(cellfun(@(x)x~=0,hhh.values))

Or you can convert the cell array of scalars to a vector via concatenation provided that everything is of the same class, as is the case in this example (see the 'UniformValues' option in containers.Map):

vals = hhh.values;
nnz([vals{:}])
horchler
  • 18,384
  • 4
  • 37
  • 73