Really easy one how to quickly repeat columns in an array

67 visualizzazioni (ultimi 30 giorni)
How do I repeat a column n times within an array to expand form 10x1 to 10x10?
e.g.
1
2
3
4
5
6
7
8
10
to
1 1 1 1 1 1 1 1 1 1 ;
2 2 2 2 2 2 2 2 2 2 ;
3 3 3 3 3 3 3 3 3 3 ;
4 4 4 4 4 4 4 4 4 4 ;
5 5 5 5 5 5 5 5 5 5 ;
6 6 6 6 6 6 6 6 6 6 ;
7 7 7 7 7 7 7 7 7 7 ;
8 8 8 8 8 8 8 8 8 8 ;
9 9 9 9 9 9 9 9 9 9 ;
10 10 10 10 10 10 10 10 10 10

Risposte (5)

Jan
Jan il 20 Giu 2018
Summary:
a = (1:1000).';
n = 1000;
tic;
for k = 1:1000
M = repmat(a, 1, n);
end
toc % 0.14 sec
tic;
for k = 1:1000
M = repelem(a, 1, n);
end
toc % 0.15 sec
tic;
for k = 1:1000
M = a * ones(1, n);
end
toc % 0.64 sec
tic;
for k = 1:1000
M = a(:, ones(1, n));
end
toc % 1.04 sec
tic;
for k = 1:1000
M = kron(a, ones(1,n));
end
toc % 0.19 sec
!!! Speed is checked in a Matlab online version - I expect it to be different on a local computer. Run it on your machine !!!

per isakson
per isakson il 21 Lug 2017
Modificato: per isakson il 21 Lug 2017
C = (1:10)';
M = repmat( C, [1,10] );
inspect the result
>> whos C M
Name Size Bytes Class Attributes
C 10x1 80 double
M 10x10 800 double

Andrei Bobrov
Andrei Bobrov il 21 Lug 2017
Modificato: Andrei Bobrov il 21 Lug 2017
a = 1:10;
out = a(:)*ones(1,10);

Jan
Jan il 19 Giu 2018
a = 1:10;
repelem(a.', 1, 10)

Musa
Musa il 19 Giu 2018
You can use the Kronecker tensor product
a=1:10;
kron(a',ones(1,10))

Categorie

Scopri di più su Function Creation in Help Center e File Exchange

Prodotti

Community Treasure Hunt

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

Start Hunting!

Translated by