Writing code to calculate difference between 2 ones in logic matrix

1 view (last 30 days)
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

Accepted Answer

per isakson
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
>>
&nbsp
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
Ali Noori
Ali Noori on 8 Jan 2015
Many thanks Sir, it is works correctly. I will be so grateful again if you help me with second attached file below:
Mohammad Abouali
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

Sign in to comment.

More Answers (1)

Image Analyst
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

Categories

Find more on Images 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!