Writing code to calculate difference between 2 ones in logic matrix
1 次查看(过去 30 天)
显示 更早的评论
Hi all, I'd like to write code to measure distance between two ones in logic matrix (1x24) attached below: I will be so grateful if someone help me. Best Regards
0 个评论
采纳的回答
per isakson
2015-1-8
编辑:per isakson
2015-1-8
A starting point
num = [0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,0];
bol = logical( num );
ix1 = find( bol );
dix = ix1(2:end)-ix1(1:end-1) - 1;
dix( dix >= 1 )
it returns
ans =
9
>>
 
Answer to comment, which basically is the solution by Mohammad Abouali with a few comments.
num = [0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0,1,1,1,0,0,0,0,0];
dn1 = diff([0,num]); % make sure the first value is zero
ix1 = find( dn1 == 1 ); % indicies of the "first ones"
dix = diff( ix1 ) -1; % distance between successive "first ones"
returns
dix =
12 9
2 个评论
Mohammad Abouali
2015-1-8
编辑:Mohammad Abouali
2015-1-8
A=[0 0 0 0 1 1 1 1 0 0 0 0 0 0 0 0 0 1 1 1 1 0 0 0 0 0 0 1 1 1 0 0 0 0 0]
diff(find(diff([0 A])>0))-1
ans =
12 9
更多回答(1 个)
Image Analyst
2015-1-8
I see you tagged it as image processing. If you want an image processing method of doing it, it would be to use regionprops to measure the "Area" (length) of the runs of zeros.
% Example 1
num = [0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,0];
% Trim off leading and trailing zeros
num = num(find(num==1, 1, 'first'):find(num==1, 1, 'last'));
% Measure the lengths of the stretches/runs of zeros.
measurements = regionprops(logical(~num), 'Area');
lengthOfZeroStretches = [measurements.Area]
% Example 2
num = [0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0,1,1,1,0,0,0,0,0];
% Trim off leading and trailing zeros
num = num(find(num==1, 1, 'first'):find(num==1, 1, 'last'));
% Measure the lengths of the stretches/runs of zeros.
measurements = regionprops(logical(~num), 'Area');
lengthOfZeroStretches = [measurements.Area]
In the command window:
lengthOfZeroStretches =
9
lengthOfZeroStretches =
9 6
0 个评论
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!