Finding out lengths of sequences of numbers in a set of vectors
11 ビュー (過去 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 で Logical についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!