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

采纳的回答

per isakson
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
>>
&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 个评论
Ali Noori
Ali Noori 2015-1-8
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 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
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

类别

Help CenterFile Exchange 中查找有关 Images 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by