need a matlab program please

1 次查看(过去 30 天)
i have a random binary matrix...... say a coloumn matrix
h= [1 1 1 0 0 0 0 0 1 0 0 1 1 0 0 1]';
i need to find the weightage of 0's and 1's.. like i need an answer like [(3,1); (5,0); (1,1); (2,0); (2,1); (2,0); (1,1)].. can u help me to get my answer in this form?
the answer matrix shows the number of 1's and 0's ... please help me to solve this problem.....

采纳的回答

Star Strider
Star Strider 2015-9-19
One approach:
h= [1 1 1 0 0 0 0 0 1 0 0 1 1 0 0 1]';
dh = diff([0; h; 0]); % Differences To Detect Start, End Of Consecutive [1,0]
hi = find(dh>0);
lo = find(dh<0);
Result = diff(sort([hi; lo])) % Sort & Take Differences
Result =
3
5
1
2
2
2
1
  3 个评论
krishan goyal
krishan goyal 2015-9-19
but what if i want to display my answer like [(3,1); (5,0); (1,1); (2,0); (2,1); (2,0); (1,1)].. can u help me to get my answer in this form?
Star Strider
Star Strider 2015-9-19
It only requires a simple change.
The updated code:
h= [1 1 1 0 0 0 0 0 1 0 0 1 1 0 0 1]';
dh = diff([0; h; 0]); % Differences To Detect Start, End Of Consecutive [1,0]
hi = find(dh>0);
lo = find(dh<0);
srthilo = sort([hi; lo]); % Sort
runs = diff(sort([hi; lo])); % Take Differences
Result = [runs h(srthilo(1:length(runs)))]
3 1
5 0
1 1
2 0
2 1
2 0
1 1

请先登录,再进行评论。

更多回答(2 个)

Walter Roberson
Walter Roberson 2015-9-19
diff(find(diff([~h(1); h; ~h(end)])~=0))
for labeling, h(1) is the first label and the rest will always alternate between 0 and 1. Odd numbered positions will be h(1) and even numbered positions will be ~h(1)
  2 个评论
krishan goyal
krishan goyal 2015-9-19
but what if i want to display my answer like [(3,1); (5,0); (1,1); (2,0); (2,1); (2,0); (1,1)].. can u help me to get my answer in this form?
Walter Roberson
Walter Roberson 2015-9-19
I already did help you about that. I pointed out how to determine the labels. The rest of it is string formatting, unless you are willing to settle for a 2D matrix [3, 1; 5, 0; 1, 1; 2, 0; 2, 1; 2, 0; 1, 1] in which case it is very easy.

请先登录,再进行评论。


Jacky Jo
Jacky Jo 2015-9-19
If you like the long coding:
A= [1 1 1 0 0 0 0 0 1 0 0 1 1 0 0 1]';
len=length(A);
A(len+1,1)=NaN;
Count_1=0; Count_0=0;
Pos=0;
for i=1:len
fprintf('\t%d',i)
if A(i,1)==1
Count_1=Count_1+1;
if A(i,1)>A(i+1,1)
Pos=Pos+1
B(Pos,1)=Count_1;
Count_1=0;
elseif i==len
Pos=Pos+1
B(Pos,1)=Count_1;
Count_1=0;
end
elseif A(i,1)==0
Count_0=Count_0+1;
if A(i,1)<A(i+1,1)
Pos=Pos+1
B(Pos,1)=Count_0;
Count_0=0;
elseif i==len
Pos=Pos+1
B(Pos,1)=Count_1;
Count_1=0;
end
end
end
fprintf('The weightage of 0s and 1s:\n');
disp(B);

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by