Effacer les filtres
Effacer les filtres

Rearrange Column of Data by Indices

1 vue (au cours des 30 derniers jours)
andyc100
andyc100 le 19 Août 2015
Modifié(e) : Star Strider le 19 Août 2015
Hi
I want to a rearrange a single column of data into multiple columns of data as defined by a variable containing the indices. The columns will be of different lengths as the interval between the indices are not constant, therefore zero padding will occur at the end of each column. For example:
A = [1 2 3 4 5 6 7 8 9 10]';
B = [2 6 8 10];
I want C to equal:
C = [2 3 4 5 6; 6 7 8 0 0; 8 9 10 0 0]';
I can achieve this via a loop:
% Determine maximum column length and initialise 'C'
index.diff = (B(2:end)-B(1:end-1));
C= zeros(max(index.diff)+1,length(B)-1);
% Loop through the number of indices and generate 'C'
for i = 1:length(B)-1
index.start = B(i);
index.end = B(i+1);
index.range = index.end - index.start;
C(1:index.range+1,i) = A(index.start:index.end);
end
Is there non-loop method to do this?
I've tried various methods including using the following help on FEX:
1. PADCAT (<http://www.mathworks.com/matlabcentral/fileexchange/22909-padcat)>, which I can't quite get that to work as the input data for that is already in separate variables.
2. INSERTROWS (<http://www.mathworks.com/matlabcentral/fileexchange/9984-insertrows--v2-0--may-2008-)>, which I use to insert the zeros first into 'A' and then reshape to get 'C', but that still requires a loop to insert the zeros (at least that's what my limited knowledge allowed me to do).
Thanks in advance

Réponses (1)

Star Strider
Star Strider le 19 Août 2015
Modifié(e) : Star Strider le 19 Août 2015
My initial intent was to use mat2cell, but the overlapping indices wouldn’t work with it. They also make non-loop options impossible.
This is a bit more efficient:
dB = diff(B)+1;
C = zeros(length(B)-1, max(dB));
for k1 = 1:size(C,1)
C(k1,1:dB(k1)) = A(B(k1):B(k1+1));
end
C =
2 3 4 5 6
6 7 8 0 0
8 9 10 0 0

Catégories

En savoir plus sur Logical 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