Effacer les filtres
Effacer les filtres

extract multiple slices of difference sizes from a vector

31 vues (au cours des 30 derniers jours)
LH
LH le 10 Juil 2024 à 14:10
Commenté : Aquatris le 10 Juil 2024 à 15:14
Hi all,
I have a vector A of the shape:
A = [1 4 6 5 4 8 7 8 6 4];
and I want to split this vector into slices. The number of slices is 3 and each slice contains a certain number of elements as follows:
num_groups = 3;
num_points_in_each_group = [2 3 5];
I want the result to be: . I have tried with the code below, but it's not working:
for i = 1:num_groups
end_count = num_points_in_each_group(i);
if i == 1
start_count = 1;
else
start_count = num_points_in_each_group(i-1) + 1;
end
A_slice = A(start_count:end_count);
end
Any help would be appreicted.
Thanks
  1 commentaire
Aquatris
Aquatris le 10 Juil 2024 à 15:14
Here is a simple modification to your code to work as intended to increase your understanding hopefully.
Since you are new, for loops might be tempting since it is easy to understand. However, keep in mind they are not efficient and you should work towards vectorization whereever possible.
A = [1 4 6 5 4 8 7 8 6 4];
num_groups = 3;
num_points_in_each_group = [2 3 5];
for i = 1:num_groups
% your end count is sum of previous group sizes and current group size
end_count = sum(num_points_in_each_group(1:i));
% your start count is 1+numberOfPointsOfPreviousGroup
start_count = 1+sum(num_points_in_each_group(1:(i-1)));
% you need to store it as cell since groups can have different number of elements
A_slice{i} = A(start_count:end_count);
end
A_slice
A_slice = 1x3 cell array
{[1 4]} {[6 5 4]} {[8 7 8 6 4]}

Connectez-vous pour commenter.

Réponses (2)

Stephen23
Stephen23 le 10 Juil 2024 à 14:21
Modifié(e) : Stephen23 le 10 Juil 2024 à 14:21
The MATLAB approach:
A = [1 4 6 5 4 8 7 8 6 4];
N = [2 3 5];
C = mat2cell(A,1,N);
Checking:
C{:}
ans = 1x2
1 4
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
ans = 1x3
6 5 4
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
ans = 1x5
8 7 8 6 4
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>

LH
LH le 10 Juil 2024 à 14:25
I think I have solved it:
A = [1 4 6 5 4 8 7 8 6 4]';
groups = 3;
end_count = cumsum(num(:));
for i = 1:groups
if i == 1
start_count = 1;
else
start_count = end_count(i-1) + 1;
end
A_slice = A(start_count:end_count(i));
end
Thanks for your help.

Catégories

En savoir plus sur Function Creation dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by