필터 지우기
필터 지우기

sum only consecutive 1's in matrix

조회 수: 4 (최근 30일)
C.G.
C.G. 2021년 10월 20일
댓글: Matt J 2021년 10월 20일
I have a matrix of data where I want to go down each column in the matrix, and sum the occurences where 1's occur consectively. E.g. if I have
1
0
1
1
0
1
1
I want this to be recorded as 1,2,2 as the groups of 1's are separated by 0's. I want this data to be stored in a new matrix where the sum data for each column is stored in a column (in the same format as the orignal data).
Is this possible?

채택된 답변

Image Analyst
Image Analyst 2021년 10월 20일
This will do it:
% Read in data.
s = load('PNM.mat')
particleNotMoved = s.particleNotMoved
% Prepare a matrix to hold our output -- the run lengths.
[rows, columns] = size(particleNotMoved)
output = zeros(floor(rows/2), columns)
% Loop over all columns, getting the run lengths of each run.
for col = 1 : columns
% Use regionprops in the Image Processing Toolbox.
props = regionprops(logical(particleNotMoved(:, col)), 'Area');
% Get the run lengths for this column.
runLengths = [props.Area]';
% Insert result for this column into our output array.
output(1:numel(runLengths), col) = runLengths;
end
  댓글 수: 3
Image Analyst
Image Analyst 2021년 10월 20일
Matrices need to be rectangular. They can't have ragged bottoms. You have to have something there, like zeros or -1's or NaNs. You could have a cell array and then have nulls/empty in there. The cells would still be there but you'd see [] in the cell instead of 0 or nan.
How are you going to use these? If you don't need to store them, then runLengths has just the numbers and you can use it immediately. Otherwise if you're using it later, after the loop, It should not be a problem to extract the column you're interested in and get just the numbers:
col = 8; % Whatever one you want
thisColumn = output(:, col); % Has trailing zeros.
runLengths = thisColumn(thisColumn > 0) % Has no trailing zeros.
C.G.
C.G. 2021년 10월 20일
Ok thank you

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Matt J
Matt J 2021년 10월 20일
See,
Tools for Processing Consecutive Repetitions in Vectors
[~,~,runlengths]=groupLims(groupTrue(particleNotMoved),1)
  댓글 수: 2
C.G.
C.G. 2021년 10월 20일
it says that my input must be a vector but im using a matrix and want it to go down the columns
Matt J
Matt J 2021년 10월 20일
An easy modification.
X=particleNotMoved;
X(end+1,:)=0;
[starts,~,runlengths]=groupLims(groupTrue(X(:)),1);
[~,G]=ind2sub(size(X),starts);
result = splitapply(@(x) {x}, runlengths,G )

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 String Parsing에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by