How to concatenate elements in cell array to a vector?

조회 수: 22 (최근 30일)
NHJ
NHJ 2022년 8월 3일
댓글: NHJ 2022년 8월 3일
I have cell arrays with different size & I want to concatenate all the elements in the cell to become a vector. How to do that?
This is my code:
% Create cell arrays
Q= [23 34; 44 55; 56 71; 63 49; 71 30];
B= [12 13; 10 99];
C{1}=Q;
C{2}=B;
% Convert cells to vector
nCol = cellfun('size', C, 1);
nRow = numel(C);
No_of_elements = cellfun(@numel, C);
P = No_of_elements(1,1) + No_of_elements(1,2);
Output = NaN(1,P); % Size vector
for iC = 1:numel(C)
idx = (iC - 1) + 1;
Output(1:P(iC), idx:idx+1) = C{iC};
end
I want the final output to become, Output = [23 34 44 55 56 71 63 49 71 30 12 13 10 99]

채택된 답변

Paul
Paul 2022년 8월 3일
Q= [23 34; 44 55; 56 71; 63 49; 71 30];
B= [12 13; 10 99];
C{1}=Q;
C{2}=B;
Output = reshape(vertcat(C{:}).',1,[])
Output = 1×14
23 34 44 55 56 71 63 49 71 30 12 13 10 99
  댓글 수: 3
Paul
Paul 2022년 8월 3일
편집: Paul 2022년 8월 3일
Q and B are not cell arrays. If you have them by themselves then
Q = [23 34 10; 44 55 45; 56 71 32; 63 49 55; 71 30 11];
B = [12 13; 10 99];
output = horzcat(reshape(Q.',1,[]),reshape(B.',1,[]))
output = 1×19
23 34 10 44 55 45 56 71 32 63 49 55 71 30 11 12 13 10 99
If they really are elements of a cell array
C{1} = Q;
C{2} = B;
output = horzcat(reshape(C{1}.',1,[]),reshape(C{2}.',1,[]))
output = 1×19
23 34 10 44 55 45 56 71 32 63 49 55 71 30 11 12 13 10 99
Probably other solutions as well.
NHJ
NHJ 2022년 8월 3일
Thank you so much. I get it

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

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

제품


릴리스

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by