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.....
댓글 수: 1
Walter Roberson
2015년 9월 19일
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
채택된 답변
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
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
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
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
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);
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Get Started with MATLAB에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!