Azzera filtri
Azzera filtri

Finding out lengths of sequences of numbers in a set of vectors

12 visualizzazioni (ultimi 30 giorni)
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

Risposte (2)

John D'Errico
John D'Errico il 17 Set 2024
Modificato: John D'Errico il 17 Set 2024
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)
uniqueV = 1×4
1 2 3 4
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
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
C = 4x1 cell array
{1x2 cell} {1x2 cell} {1x2 cell} {1x2 cell}
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{:}
ans = 1x2 cell array
{[1]} {[3 2 2]}
ans = 1x2 cell array
{[2]} {[4]}
ans = 1x2 cell array
{[3]} {[2 3]}
ans = 1x2 cell array
{[4]} {[4]}
You could have done differently. A struct might also be a good way to store the data.

Poojith
Poojith il 17 Set 2024
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
1
3 2 2
2
4
3
2 3
4
4

Categorie

Scopri di più su Characters and Strings in Help Center e File Exchange

Prodotti


Release

R2024a

Community Treasure Hunt

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

Start Hunting!

Translated by