Hello,
I'm trying to use the repelem function to repeat some columns of a matrix A like:
A = [1 2 3 4; 5 6 7 8];
If I use the repelem function I'll get the following output:
out = repelem(A,1,2);
out =
[1 1 2 2 3 3 4 4 ; 5 5 6 6 7 7 8 8]
However I'm trying to repeat two columns at the same time instead of doing it individually. So that I get an output like:
Output = [1 2 1 2 3 4 3 4; 5 6 5 6 7 8 7 8]
Anyone can come around a solution to this problem?
Thank you,
Santos

 採用された回答

David Hill
David Hill 2021 年 4 月 22 日

0 投票

out=[repmat(A(:,1:2),1,2),repmat(A(:,3:4),1,2)];

5 件のコメント

Santos García Rosado
Santos García Rosado 2021 年 4 月 22 日
Thank's for your quick answer @David Hill. But what if I have a very long matrix? Isn't there a more automated way of doing it? Thank you again. Santos.
David Hill
David Hill 2021 年 4 月 22 日
out=[];
for k=2:2:size(A,2)
out=[out,repmat(A(:,k-1:k),1,2)];
end
Santos García Rosado
Santos García Rosado 2021 年 4 月 22 日
So it seems like a loop is inevitable then. I'll try to find a way around that loop. Thank you David!
David Hill
David Hill 2021 年 4 月 22 日
You could reshape, not sure it will be any faster.
out=reshape(repelem(reshape(A',2,[]),1,2),2*size(A,2),[])';
Santos García Rosado
Santos García Rosado 2021 年 4 月 23 日
I'll take a good look at it. Thank you David.

サインインしてコメントする。

その他の回答 (1 件)

Wolfgang
Wolfgang 2022 年 6 月 24 日

0 投票

Here is a more generalized solution which duplicates pairs of columns and doesn't depend on the number of columns, however the number of columns in A has to be even.
B = reshape(kron(ones(2,1), reshape(A, 2*size(A,1), [])), size(A,1), []);
This also allows to triplicate pairs of columns by using:
B = reshape(kron(ones(3,1), reshape(A, 2*size(A,1), [])), size(A,1), []);
Or you can triplicate triples of columns (number of columns in A must be a multiple of 3):
B = reshape(kron(ones(3,1), reshape(A, 3*size(A,1), [])), size(A,1), []);
Also possible: duplicate triples of columns:
B = reshape(kron(ones(2,1), reshape(A, 3*size(A,1), [])), size(A,1), []);
And so on ...

カテゴリ

ヘルプ センター および File ExchangeMatrix Indexing についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by