need a matlab program please
2 views (last 30 days)
Show older comments
krishan goyal
on 19 Sep 2015
Commented: Star Strider
on 19 Sep 2015
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.....
1 Comment
Walter Roberson
on 19 Sep 2015
That would normally be referred to as "run length encoding". And it is clearly a homework assignment. As what have you come up with? http://www.mathworks.com/matlabcentral/answers/6200-tutorial-how-to-ask-a-question-on-answers-and-get-a-fast-answer
Accepted Answer
Star Strider
on 19 Sep 2015
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 Comments
Star Strider
on 19 Sep 2015
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
More Answers (2)
Walter Roberson
on 19 Sep 2015
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 Comments
Walter Roberson
on 19 Sep 2015
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
on 19 Sep 2015
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);
0 Comments
See Also
Categories
Find more on Get Started with MATLAB in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!