开发者

Expression for summing all the entries of a logical matrices expressions in Matlab?

开发者 https://www.devze.com 2023-04-09 21:16 出处:网络
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

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.


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

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


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',{{':'}})) )
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号