Finding out lengths of sequences of numbers in a set of vectors
조회 수: 5 (최근 30일)
이전 댓글 표시
Not sure what is the most efficient way to do this. I have a set of vectors consisting only of the numbers 1, 2, 3, 4, 5, 6, 7 and 8 in various permutations. For each vector, I need to find out the length of each sequence of each number. E.g. if my vector was
[1 1 1 3 3 1 1 4 4 4 4 1 1 3 3 3 2 2 2 2]
Then I would need to obtain an output that looks something like this:
1 3 2 2
2 4
3 2 3
4 4
댓글 수: 0
답변 (2개)
John D'Errico
2024년 9월 17일
편집: John D'Errico
2024년 9월 17일
It took a few seconds staring at the output you expect to see, and realize what you meant. I THINK the first element in each row of that output gives you the number in question, and then the rest of the elements in that row are the respective lengths of the corresponding subsequences.
Nothing stops you from using a loop however! First, find the set of elements you need to consider. unique gives you that simply enough.
V = [1 1 1 3 3 1 1 4 4 4 4 1 1 3 3 3 2 2 2 2];
uniqueV = unique(V)
Next, you can simply loop over the elements of uniqueV. For example, when V == 1, where does each segment start and end? You can use tools like strfind to locate those indices.
C = cell(numel(uniqueV),1);
for ind = 1:numel(uniqueV)
vloc = V == uniqueV(ind);
substrlengths = strfind([vloc,0],[1 0]) - strfind([0,vloc],[0 1]) + 1;
C{ind} = {uniqueV(ind),substrlengths};
end
C
And that is effectively what you want. I chose to use a cell array to store the result, where each cell is split into another cell array.
C{:}
You could have done differently. A struct might also be a good way to store the data.
댓글 수: 0
Poojith
2024년 9월 17일
Hey,
You can do this way.
vector = [1 1 1 3 3 1 1 4 4 4 4 1 1 3 3 3 2 2 2 2, 0];
change_indices = find(diff(vector) ~= 0);
lengths = diff([0, change_indices]);
values = vector(change_indices);
for num = 1:8
seq = lengths(values == num);
if ~isempty(seq)
fprintf('%d ', num);
fprintf('%d ', seq);
fprintf('\n');
end
end
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Characters and Strings에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!