how to find the number of 1 in a single column?

4 次查看(过去 30 天)
My input is
0 0 0 0 1 0 0 1 1 0 0 0 1 0
I should find how many 1 is present

回答(6 个)

Jan
Jan 2012-9-5
编辑:Jan 2012-9-5
If it is a string:
c = '0 0 0 0 1 0 0 1 1 0 0 0 1 0';
s = sum(c == '1');
% or:
s = length(strfind(c, '1');
if it is a numeric vector:
c = [0 0 0 0 1 0 0 1 1 0 0 0 1 0];
s = sum(c); % as Jose-Luis has suggested already
% or:
s = nnz(c);

José-Luis
José-Luis 2012-9-5
编辑:José-Luis 2012-9-5
your_answer = sum(your_input)

Azzi Abdelmalek
Azzi Abdelmalek 2012-9-5
c='0 0 0 0 1 0 0 1 1 0 0 0 1 0'
sum(str2num(c))

Sivakumaran Chandrasekaran
Thanks for all replies...
1 1
1 2
3 1
2 1
3 1
1 2
3 2
2 1
3 1
2 1
3 2
2 2
3 1
2 2

Sivakumaran Chandrasekaran
thats my input matrix.. let me take query input as 1 1... now i have to check this 1 1 with all the rows of the given input matrix.. I have find the rows which matches this input.
  2 个评论
Sivakumaran Chandrasekaran
when i take the first row as the query one, and if i found it is matching with 5th, then output should be displayed as [1,5]

请先登录,再进行评论。


Matt Tearle
Matt Tearle 2012-9-5
编辑:Matt Tearle 2012-9-5
idx = find(all(bsxfun(@eq,x,y),2));
where x is your matrix and y is your test vector (eg y = x(1,:), in your example). For example
x = randi(4,1000,5);
y = x(3,:);
idx = find(all(bsxfun(@eq,x,y),2))

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

标签

产品

Community Treasure Hunt

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

Start Hunting!

Translated by