How to extend a array by multiplying internal values e.g. [1 2 3 4] to [1 1 1 2 2 2 3 3 3 4 4 4]?
Mostrar comentarios más antiguos
How can I extend this array:
A = [1 2 3 4 5 6 7]
So that a new array can be formed in which each value of array A appears 4 times, and the array keeps its order? E.g. for array A the result would be:
B = [1 1 1 1 2 2 2 2 3 3 3 3 4 4 4 4 5 5 5 5 6 6 6 6 7 7 7 7]
Thanks for any advice :)
Respuestas (4)
Roger Stafford
el 30 de Dic. de 2014
Editada: Roger Stafford
el 31 de Dic. de 2014
B = A(ceil((1:4*size(A,2))/4)); % <--- Corrected
Sean de Wolski
el 30 de Dic. de 2014
B = kron(A,ones(1,4))
Or
B = reshape(repmat(A,4,1),1,[])
1 comentario
Jan
el 31 de Dic. de 2014
According to the definition of the problem kron() is the direct solution in a mathematical manner. From the view point of a software engineer, the numerical multiplication is an indirection here and repmat avoids them. Therefore I prefer both solutions.
Stephen23
el 30 de Dic. de 2014
I don't know how this compares for speed, but it gets the desired result using some basic MATLAB matrix multiplication:
>> A = [1 2 3 4 5 6 7];
>> B = [1;1;1;1] * A;
>> B = B(:).'
ans = [1 1 1 1 2 2 2 2 3 3 3 3 4 4 4 4 5 5 5 5 6 6 6 6 7 7 7 7]
Azzi Abdelmalek
el 30 de Dic. de 2014
A = [1 2 3 4 5 6 7]
B=bsxfun(@times,ones(4,1),A);
out=B(:)'
2 comentarios
Sean de Wolski
el 30 de Dic. de 2014
I'd expect
bsxfun(@plus,zeros(4,1),A)
to be faster.
Azzi Abdelmalek
el 30 de Dic. de 2014
Exact, but the repmat solution is faster
Categorías
Más información sobre Matrices and Arrays en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!