Finding out lengths of sequences of numbers in a set of vectors
12 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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 Commenti
Risposte (2)
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)
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 Commenti
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
0 Commenti
Vedere anche
Categorie
Scopri di più su Characters and Strings in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!