0

To sum all the elements in a matrix you usually do

A = sum ( B(:) );

which is nice and short. However assume that we have a logical expression like this

B = B == 6 

and we want to sum the elements of all the entries, then smartest way seems to be to do

A = sum ( sum ( B == 6 ) )

or

B = B == 6;
A = sum( B(:) );

Both are kind of ugly. So I was wondering is there a nicer expression?

A = sum ( (B == 6)(:) );

Would be nice but doesn't work.

Reed Richards
  • 4,178
  • 8
  • 41
  • 55

2 Answers2

3

So what is so nasty about the simple solution...

A = sum(B(:) == 6);
0

Not that I recommend this, but as was shown previously, you can actually do something like:

%# A = sum ( (B == 6)(:) )
A = sum( subsref(B == 6, struct('type','()', 'subs',{{':'}})) )
Community
  • 1
  • 1
Amro
  • 123,847
  • 25
  • 243
  • 454