How to create a vector from two vectors?

5 visualizaciones (últimos 30 días)
DS Chen
DS Chen el 30 de Ag. de 2016
Comentada: DS Chen el 30 de Ag. de 2016
I have two vectors with the same length:
A = [2 4 5 4 9 8 1 6];
B = [3 6 2 5 4 4 3 5];
Each element in vector B defines how many times the corresponding element in vector A duplicates itself. For example, here I want the final vector C to have 3 twos, 6 fours, 2 fives, 5 fours, 4 nines, 4 eights, 3 ones, and 5 sixes:
C = [2 2 2, 4 4 4 4 4 4, 5 5, 4 4 4 4 4, 9 9 9 9, 8 8 8 8, 1 1 1, 6 6 6 6 6];
I can do it with a for-loop. However in practice, vectors A and B are long. So is there a way to do this without a loop.
Thanks!

Respuesta aceptada

Stephen23
Stephen23 el 30 de Ag. de 2016
Editada: Stephen23 el 30 de Ag. de 2016
If you have MATLAB 2015a or more recent then use repelem:
repelem(A,B)
otherwise:
cell2mat(arrayfun(@(a,b)repmat(a,1,b),A,B,'Uni',0))
although a loop may well be faster.
  3 comentarios
Stephen23
Stephen23 el 30 de Ag. de 2016
Editada: Stephen23 el 30 de Ag. de 2016
Important: do NOT expand the array in the loop! Use a preallocated cell array:
>> C = cell(size(A));
>> for k = 1:numel(C), C{k} = repmat(A(k),1,B(k)); end
>> cell2mat(C)
Or a preallocated numeric array (this is faster):
>> X = cumsum([0,B]);
>> D = NaN(1,X(end));
>> for k = 1:numel(A), D(1+X(k):X(k+1)) = A(k); end
DS Chen
DS Chen el 30 de Ag. de 2016
Good Point!
Using preallocated cell array is 40 times faster than expanding array in the loop.
I also test the repelem(A, B) on the other machine. repelem(A,B) is indeed the fastest! It's at least 10 times faster than for-loop. I hope I can use it later:)

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by