counting data points

9 次查看(过去 30 天)
Sonia Wiemann
Sonia Wiemann 2012-4-24
I have a data set of 1's and 0's like this 000001111100000111110000011111000001111100000 this data set is called "c"
I need the program to output a count of sections so to speak. In this example they are all even and short but in my data set they are extremely long and of varying lengths. If I could get an output like 5,5,5,5,5,5,5 counting each section it would save me tons of time.

采纳的回答

Image Analyst
Image Analyst 2012-4-25
If you have the "c" as an integer or logical array, and if you have the Image Processing Toolbox, you can do it in one line with regionprops(). Just simply say "measurements = regionprops(~c, 'Area')" Here's a full demo:
% Create sample data.
c = [0 0 0 0 0 1 1 1 1 1 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0]
% Measure the zero sections - KEY LINE OF CODE RIGHT HERE!
measurements = regionprops(~c, 'Area')
% Display results.
fprintf('The number of zero sections is %d.\n', length(measurements));
fprintf('The sizes of zero sections are:\n');
allAreas = [measurements.Area]
  1 个评论
Sonia Wiemann
Sonia Wiemann 2012-4-26
Thanks a lot! This will save loads of time counting thousands of zeros!

请先登录,再进行评论。

更多回答(2 个)

per isakson
per isakson 2012-4-24
I learned this trick the other day:
str = '11110111000001111100000111110000011111000001111100000';
cac = regexp( str, '0+', 'split' );
n = cellfun( @(s) length(s), cac )
n =
4 3 5 5 5 5 0
You might want to check for leading and trailing 0. If the string is huge you might need to split it.
--- EDIT without the Image Processing Toolbox ---
c = round( rand( 1,100 ) + 0.1 ); % Sample data
str = sprintf( '%1u', c );
cac = regexp( str, '0+', 'split' );
len = cellfun( @(s) length(s), cac );

Andrei Bobrov
Andrei Bobrov 2012-4-25
str = '11110111000001111100000111110000011111000001111100000';
x = str -'0';
k = find([true, diff(x)~=0]);
out = [x(k); diff([k;[k(2:end),numel(x)+1]])]
OR
out = diff([find([true, diff(x)~=0]) numel(x)+1]);
ADDED with use regexp
out = cellfun('length',regexp(str,'(0*|1*)','match'))

类别

Help CenterFile Exchange 中查找有关 Data Type Conversion 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by