Build matrix from corresponding table variables stored in cell array

12 vues (au cours des 30 derniers jours)
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

Réponse acceptée

Matt J
Matt J le 3 Sep 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>
  1 commentaire
Cristian Berceanu
Cristian Berceanu le 3 Sep 2025
I like this one much better, thanks! 9ms execution time is not so bad.
Cristian

Connectez-vous pour commenter.

Plus de réponses (1)

Matt J
Matt J le 3 Sep 2025
Modifié(e) : Matt J le 3 Sep 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>

Catégories

En savoir plus sur Matrices and Arrays dans Help Center et File Exchange

Tags

Produits


Version

R2024b

Community Treasure Hunt

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

Start Hunting!

Translated by