Info

この質問は閉じられています。 編集または回答するには再度開いてください。

I want to copy some data

1 回表示 (過去 30 日間)
pty0220
pty0220 2017 年 8 月 7 日
閉鎖済み: MATLAB Answer Bot 2021 年 8 月 20 日
I want to copy some data
if i have a data(matrix) like this ,,
2 3 4
6 2 3
9 8 3
I would like to copy this data like this ,,
2 3 4
2 3 4
2 3 4
2 3 4
6 2 3
6 2 3
6 2 3
6 2 3
9 8 3
9 8 3
9 8 3
9 8 3
This is easy to solve if I use the 'for loop' But I will work with very large data ,so speed is very important for me... Is there any way to solve this problem without 'for loop'??
  1 件のコメント
Adam
Adam 2017 年 8 月 7 日
Where speed is critical I would always recommend putting together a script/function to test the various different alternatives on different data sizes because results can often be unexpected with regard to how fast certain implementations are.
Creating a quick function with subfunctions that implement each of the alternatives to use with
doc timeit
is very simple. All you need then is the ideas for alternative implementations, of which you now have 4 (always include the for loop option for timing too - it isn't guaranteed not to be fastest)

回答 (3 件)

Adam
Adam 2017 年 8 月 7 日
編集済み: Adam 2017 年 8 月 7 日
a = [2 3 4; 6 2 3; 9 8 3];
b = repelem( a, 4, 1 );
If you are using R2015a or later. I haven't tested it for speed against a for loop though. As a built-in Matlab function it should be faster, but no guarantees.
  1 件のコメント
Jan
Jan 2017 年 8 月 7 日
編集済み: Jan 2017 年 8 月 7 日
+1. This is the job of repelem. I cannot compare the speed currently with the less nice:
Result = M(repmat(1:size(M,1), N, 1), :);

José-Luis
José-Luis 2017 年 8 月 7 日
編集済み: José-Luis 2017 年 8 月 7 日
a = [2 3 4; 6 2 3; 9 8 3];
idx = ndgrid(1:3,1:4)';
result = a(idx(:),:)
Edit: Felt the nagging need for a one-liner, not repeating existing answers:
result = a(idivide(int32(0:11),4)+1,:)

Jan
Jan 2017 年 8 月 7 日
編集済み: Jan 2017 年 8 月 7 日
N = 4;
M = [2,3,4;6,2,3;9,8,3];
index = repmat(1:size(M,1), N, 1);
Result = M(index, :);
Or:
kron(M, ones(M, 1))
The indexing should be efficient, while I expect kron to be remarkably slower. repelem is the command explicitly defined for this job, so I prefer Adam's solution if you have a modern Matlab version. If this is the bottleneck of the code, it is worth to check, which solution is the fastest.

この質問は閉じられています。

Community Treasure Hunt

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

Start Hunting!