Build matrix from corresponding table variables stored in cell array

5 visualizaciones (últimos 30 días)
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

Respuesta aceptada

Matt J
Matt J el 3 de Sept. de 2025
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>

Más respuestas (1)

Matt J
Matt J el 3 de Sept. de 2025
Editada: Matt J el 3 de Sept. de 2025
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>

Categorías

Más información sobre Matrices and Arrays en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2024b

Community Treasure Hunt

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

Start Hunting!

Translated by