need a matlab program please
2 ビュー (過去 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 で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!