Writing code to calculate difference between 2 ones in logic matrix
1 view (last 30 days)
Show older comments
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 Comments
Accepted Answer
per isakson
on 8 Jan 2015
Edited: per isakson
on 8 Jan 2015
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 Comments
Mohammad Abouali
on 8 Jan 2015
Edited: Mohammad Abouali
on 8 Jan 2015
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
More Answers (1)
Image Analyst
on 8 Jan 2015
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 Comments
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!