repelem substitute for older matlab version

11 ビュー (過去 30 日間)
MiauMiau
MiauMiau 2017 年 6 月 24 日
コメント済み: KSSV 2017 年 6 月 24 日
Hi,
I want to do the following (what usually repelem does, however an older version of Matlab does not seem to have it):
Given vector a = [3 45 6 ];
I would want for instance its first element to be repeated 2 times, the second 4 times, the third element once (just as an example). So we would end up with:
aNew = [3 3 4 45 45 45 6 6];
How can that be done in a systematic way without repelem?
Thanks
  1 件のコメント
Stephen23
Stephen23 2017 年 6 月 24 日
You say that you want "the third element once", but it appears twice in your example. Which is correct? Where does that 4 come from?

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

回答 (2 件)

Stephen23
Stephen23 2017 年 6 月 24 日
>> A = [3,45,6];
>> R = [2,4,1];
>> cell2mat(arrayfun(@(a,r)repmat(a,1,r),A,R,'uni',0))
ans =
3 3 45 45 45 45 6
  1 件のコメント
KSSV
KSSV 2017 年 6 月 24 日
+1

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


KSSV
KSSV 2017 年 6 月 24 日
a = [3 45 6 ];
aNew = [3 3 45 45 45 45 6 6];
R = [2 4 3] ;
iwant = [] ;
for i = 1:length(R)
iwant = [iwant ones(1,R(i))*a(i)] ;
end
  2 件のコメント
Stephen23
Stephen23 2017 年 6 月 24 日
Expanding arrays within loops is not recommended:
See my answer for a one-line solution that does not expand arrays inside loops.
KSSV
KSSV 2017 年 6 月 24 日
a = [3 45 6 ];
aNew = [3 3 45 45 45 45 6 6];
R = [2 4 3] ;
iwant = cell(1,length(R)) ;
for i = 1:length(R)
iwant{i} = ones(1,R(i))*a(i) ;
end
iwant = [iwant{:}]

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

カテゴリ

Help Center および File ExchangeMatrices and Arrays についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by