Build matrix from corresponding table variables stored in cell array

4 ビュー (過去 30 日間)
Cristian Berceanu
Cristian Berceanu 2025 年 9 月 3 日
コメント済み: Cristian Berceanu 2025 年 9 月 3 日
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 件のコメント
Cristian Berceanu
Cristian Berceanu 2025 年 9 月 3 日
I like this one much better, thanks! 9ms execution time is not so bad.
Cristian

サインインしてコメントする。

その他の回答 (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 Center および File ExchangeMatrices and Arrays についてさらに検索

タグ

製品


リリース

R2024b

Community Treasure Hunt

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

Start Hunting!

Translated by