How to store a cell array as a table cell?

26 views (last 30 days)
azarang asadi
azarang asadi on 19 Oct 2022
Answered: Eshan Patel on 3 Nov 2022
Hi all,
I have a structure with 5 fileds:
struct.field1 --> 1*8 cell
struct.field2 --> singe value (double)
struct.field3 --> 1*8 cell
struct.field4 --> 1*8 matrix (double)
struct.field5 --> 1*8 cell
and I also have a string let's call it RowName.
Now what I'm trying to do is to create a table with 6 variables and do a for loop which fills each row at each iteration. in each iteration, we need to do some calculations to get the struct and then assign its fileds to a row of the table. Here's how I did it:
T = table('Size',[0,6], 'VariableTypes',{'string','cell', 'double', 'cell', 'cell', 'cell'}, 'VariableNames',{'name','Var1', 'Var2', 'Var3', 'Var4', 'Var5'});
for i = 1:endLoop
T(end+1,:) = {RowName, struct.field1, struct.field2, struct.field3, {struct.field4}, struct.field5};
this doesn't work so I wonder how I can do it.
Also one more question:
struct.field4 is originally a 1*8 vector (double). Can I store it as a vector not a cell in my table? cause the code above stores it as a cell.
Thank you.
  1 Comment
dpb on 19 Oct 2022
"struct.field4 is originally a 1*8 vector (double). Can I store it as a vector not a cell in my table?"
No. A given row for in a table for a variable is only one storage location -- the scalar cell variable contaiming the vector is that one thing that can go there.
This doesn't appear to be a good fit for the table class...

Sign in to comment.

Answers (1)

Eshan Patel
Eshan Patel on 3 Nov 2022
Hey Azarang,
I understand that you would like to save the values from the struct into a table. Since the struct has 5 fields (+ "rowName"), I am assuming you would like to have 6 columns (variables), and 8 rows to represent the 8 values in your fields.
To achieve this, you can use the following snippet of code:
T = table('Size', [8, 6], 'VariableTypes', ["string", "double", "double", "double", "double", "string"], ...
'VariableNames',{'name','Var1', 'Var2', 'Var3', 'Var4', 'Var5'});
for i = 1:8
T(i, :) = {rowName{i}, struct.field1{i}, struct.field2, ...
struct.field3{i}, struct.field4(i), struct.field5{i}};
assuming "rowName" is also a vector of strings.
To answer your second question - whether it would be possible to store "struct.field4" as a vector - no, it would not be possible to store your original vector field as a vector. However, you can obtain the vector back from the table using the following line of code:
a = [T{:, "Var4"}].';
% or
b = table2array(T(:, "Var4")).';


Find more on Cell Arrays in Help Center and File Exchange




Community Treasure Hunt

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

Start Hunting!