Writing code to calculate difference between 2 ones in logic matrix

1 Ansicht (letzte 30 Tage)
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

Akzeptierte Antwort

per isakson
per isakson am 8 Jan. 2015
Bearbeitet: per isakson am 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 Kommentare
Ali Noori
Ali Noori am 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 am 8 Jan. 2015
Bearbeitet: Mohammad Abouali am 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

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

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

Kategorien

Mehr zu Images finden Sie in Help Center und File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by