Build matrix from corresponding table variables stored in cell array

조회 수: 15 (최근 30일)
Hello, I have a number of tables with identical variables, stored as elements in a cell array. For example:
NoOfCells = randi([5 10]); % generate number of tables
C = cell(NoOfCells,1); % preallocate
% generate cell array of tables with same variable names
for i = 1:NoOfCells
A = rand(3);
T = array2table(A);
T.Properties.VariableNames = {'Col1' 'Col2' 'Col3'};
C{i,1} = T;
end
Wht I would like to now do is build a matrix from Col1 of each table, essentially wihtout using a for loop (I know how to do it with a for loop).
I was thinking somehting like:
D = [C{:}.Col1]
This unfortunatelly produces: Intermediate brace '{}' indexing produced a comma-separated list with 8 values, but it must produce a single value when followed by subsequent indexing operations.
How could it be done?
Regards,
Cristian

채택된 답변

Matt J
Matt J 2025년 9월 3일
load data
D=reshape( vertcat(C{:}).Col1 , height(C{1}) ,[])
D = 3×9
0.9058 0.1576 0.9595 0.6555 0.3171 0.4456 0.4984 0.8909 0.2435 0.1270 0.9706 0.6557 0.1712 0.9502 0.6463 0.9597 0.9593 0.9293 0.9134 0.9572 0.0357 0.7060 0.0344 0.7094 0.3404 0.5472 0.3500
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>

추가 답변 (1개)

Matt J
Matt J 2025년 9월 3일
편집: Matt J 2025년 9월 3일
I hope you understand that speed-wise there is no way to iterate over cell arrays that is faster than a for-loop. However, using cellfun can abbreviate the syntax of a for-loop:
load data; whos C
Name Size Bytes Class Attributes C 9x1 15039 cell
disp(C{1})
Col1 Col2 Col3 _______ _______ _______ 0.90579 0.63236 0.54688 0.12699 0.09754 0.95751 0.91338 0.2785 0.96489
D=cell2mat( cellfun(@(t) t.Col1, C', 'uni',0) )
D = 3×9
0.9058 0.1576 0.9595 0.6555 0.3171 0.4456 0.4984 0.8909 0.2435 0.1270 0.9706 0.6557 0.1712 0.9502 0.6463 0.9597 0.9593 0.9293 0.9134 0.9572 0.0357 0.7060 0.0344 0.7094 0.3404 0.5472 0.3500
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>

카테고리

Help CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

태그

제품


릴리스

R2024b

Community Treasure Hunt

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

Start Hunting!

Translated by