Expanding Cell Array using repmat with a loop

2 ビュー (過去 30 日間)
Jorge Rodriguez
Jorge Rodriguez 2017 年 9 月 5 日
コメント済み: Image Analyst 2017 年 9 月 5 日
Hello Community, I'm trying to expand a column vector A([4,5,9,8],1) by using different sizes hold in a vector B([40,10,20,70],1) and creating a vector C([4,4,4...40x,5,5,5...10x,9,9,9...20x,8,8,8,...70x],1). I'm tryig to achieve this by using a loop and repmat.
clc
A=[4;5;9;8];
B=[40;10;20;70];
R=0;
k=size(A,1);
for h=1:k
C(R+1,1)=repmat(A(h,1),B(h,1),1);
R=B(h,1);
end
The error message shows: "Assignment has more non-singleton rhs dimensions than non-singleton subscripts"
  1 件のコメント
Walter Roberson
Walter Roberson 2017 年 9 月 5 日
Why not use repelem()?

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

採用された回答

Image Analyst
Image Analyst 2017 年 9 月 5 日
You need to use braces with C since it's a cell array. And C must be a cell array since it will have different numbers of elements in each element of A and B.
clc
A=[4;5;9;8];
B=[40;10;20;70];
for k = 1 : length(A)
C{k} = repmat(A(k),[1, B(k)]);
end
celldisp(C)
  2 件のコメント
Jorge Rodriguez
Jorge Rodriguez 2017 年 9 月 5 日
thanks for the help, it moves me forward in the solution I'm looking for. But I need that the cell array C be a continuous array with the values of A continuous, in other words one column for C with values 4,4,4,4....5,5,5,5.....,9,9,9,9.....,8,8,8,8,8.... so the lenght of vector C should be (140,1)
Image Analyst
Image Analyst 2017 年 9 月 5 日
Sorry, your terminology where you had arrays inside your C "C([4,4,4...40x,5,5,5...10x,9,9,9...20x,8,8,8,...70x],1)" threw me. So just use repelem() like Walter and Andrei told you.

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

その他の回答 (1 件)

Andrei Bobrov
Andrei Bobrov 2017 年 9 月 5 日
編集済み: Andrei Bobrov 2017 年 9 月 5 日
with loop for..end
A=[4;5;9;8];
B=[40;10;20;70];
n = cumsum(B);
m = n - B + 1;
k = size(B,1);
C = zeros(n(end),1);
for h=1:k
C(m(h):n(h),1)=repmat(A(h),B(h),1);
end
without loop
A = [4;5;9;8];
B = [40;10;20;70];
n = cumsum(B);
m = n - B + 1;
ii = zeros(n(end),1);
ii(m) = 1;
C = A(cumsum(ii));
or just
C = repelem(A,B);

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by