Repeating elements (vector)
古いコメントを表示
Hi everyone,
Suppose I have matrix A
A = [1; 2; 3; 4]
And I want to have matrix B
B = [1; 1; 2; 1; 2; 3; 1; 2; 3; 4]
I don't want to use loop to do so because I have lots of observations. So how can I do this efficiently without using loop? Thank you very much!
Jeff
5 件のコメント
Stephen23
2017 年 1 月 19 日
@Tsz Heung: what is the rule to generate B from A ?
Tsz Heung
2017 年 1 月 19 日
Adam
2017 年 1 月 19 日
I assume the rule is you want just the 1st row, then the first 2 rows, then the first 3 rows, etc, all collapsed into a single vector.
Jan
2017 年 1 月 19 日
@Tsz Heung: There is an infinite number of methods to create B based on A from your example. To create a program, we have to know the definition of the procedure. One example is not enough to define this unequivocally.
@Adam: You mean:
- one time the first row
- one time the first 2 rows
- two times the first 3 rows
- one time the last row
???
採用された回答
その他の回答 (1 件)
Walter Roberson
2017 年 1 月 19 日
nonzeros(triu(repmat(A,1,length(A))))
Note: this assumes that none of the entries are 0.
2 件のコメント
+1 very nice. It would be interesting to know if repmat or multiply is faster:
nonzeros(triu((1:N)'*ones(1,N)))
Tsz Heung
2017 年 1 月 19 日
カテゴリ
ヘルプ センター および File Exchange で Creating and Concatenating Matrices についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!