Distributing a cell array into another

조회 수: 1 (최근 30일)
Jerki Jokne
Jerki Jokne 2020년 5월 18일
답변: Star Strider 2020년 5월 18일
If I have 2 cell arrays of chars, is it possible to distribute them such that they are combined and concatenated?
A = {'Category1', 'Category2'};
B = {'Mon', 'Tues', 'Wed', 'Thurs' 'Fri', 'Sat', 'Sun'};
Result = {'Category1 Mon', 'Category1 Tues', ..., 'Category1 Sun', 'Category2 Mon', 'Category2 Tues', ..., 'Category2 Sun'};

채택된 답변

Star Strider
Star Strider 2020년 5월 18일
Adding end spaces to each character array in ‘A’ and converting them to string arrays:
A = {'Category1 ', 'Category2 '};
B = {'Mon', 'Tues', 'Wed', 'Thurs' 'Fri', 'Sat', 'Sun'};
then transposing ‘A’ and adding them:
Result = string(A).' + string(B)
produces:
Result =
2×7 string array
Columns 1 through 4
"Category1 Mon" "Category1 Tues" "Category1 Wed" "Category1 Thurs"
"Category2 Mon" "Category2 Tues" "Category2 Wed" "Category2 Thurs"
Columns 5 through 7
"Category1 Fri" "Category1 Sat" "Category1 Sun"
"Category2 Fri" "Category2 Sat" "Category2 Sun"
Otherwise, the only option is likely two nested loops, concatenating elements of ‘A’ and ‘B’ in each iteration to form elements of ‘Result’.
.

추가 답변 (2개)

the cyclist
the cyclist 2020년 5월 18일
편집: the cyclist 2020년 5월 18일
Here is a straightforward way:
A = {'Category1', 'Category2'};
B = {'Mon', 'Tues', 'Wed', 'Thurs' 'Fri', 'Sat', 'Sun'};
nA = numel(A);
nB = numel(B);
Result = cell(1,nA*nB);
nc = 0;
for ia = 1:nA
for ib = 1:nB
nc = nc + 1;
Result{nc} = [A{ia},' ',B{ib}];
end
end

Fangjun Jiang
Fangjun Jiang 2020년 5월 18일
strcat(repmat(A,size(B')),repmat({' '},[length(B),length(A)]),repmat(B',size(A)))

카테고리

Help CenterFile Exchange에서 MATLAB에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by