problem for creating vector with for loop

1 回表示 (過去 30 日間)
sermet
sermet 2014 年 4 月 29 日
コメント済み: José-Luis 2014 年 4 月 29 日
a={'w','c','e'};
%I wanna create 2 times of w,c,e, with using for loop, like this
aa={'w','w','c','c','e','e'};

採用された回答

José-Luis
José-Luis 2014 年 4 月 29 日
a={'w','c','e'};
nRep = 5;
your_mat = reshape(repmat(a,nRep,1),1,[]);

その他の回答 (2 件)

Justin
Justin 2014 年 4 月 29 日
編集済み: Justin 2014 年 4 月 29 日
This is not a difficult task to do but does take a little extra planning in how to index the first array.
I'll give you an example of one way to do it but you should try another way as well.
% first define aa as an empty cell
aa = {};
% then create a loop for each element of your original matrix
for i = 1:length(a)
% now concatenate your aa array with the repeated elements of a (you can just write a(i) twice)
aa = [aa a(i) a(i)];
end
Other options may be to use repmat, reshape, or indexing differently using a modulo of 2 to increment your index of the original array.
Some of these options will be more robust and able to work when you want to make a triple copy or other elements of your input vary.
  1 件のコメント
sermet
sermet 2014 年 4 月 29 日
編集済み: sermet 2014 年 4 月 29 日
I gave 2 for just an example, actual repeating times depends on the situation. For example I wanna repeat 4 and I wanna use repmat, could you show me how I can use repmat for a?

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


Jos (10584)
Jos (10584) 2014 年 4 月 29 日
Many roads to Rome:
A = {'w' 'c' 'e'}
n = 2
AA1 = A(kron(1:numel(A),ones(1,n)))
AA2 = reshape(repmat(A,n,1),1,[])
AA3 = A(ceil(linspace(1/n,numel(A),n*numel(A))))
  1 件のコメント
José-Luis
José-Luis 2014 年 4 月 29 日
:)
Maybe we should start a thread with the most complicated ways to solve this problem.

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

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by