Reputation: 327
I try to use a vector as a column in a table (in MATLAB). However, I always get different errors. Below is a reproducible example, together with the recieved errors:
% What I have:
my_table = array2table(NaN(5, 3));
my_table.Properties.VariableNames = {'col_1' 'col_2' 'col_3'};
my_cell = {'a', 'b', 'c', 'd', 'e'};
% What I tried:
my_table.col_3 = my_cell; %Error: To assign to or create a variable in a table, the number of rows must match the height of the table.
my_table.col_3(1:5) = my_cell; %Error: Conversion to double from cell is not possible.
my_table.col_3.Properties.VariableTypes = {'string'}; %Error: Unable to perform assignment because dot indexing is not supported for variables of this type.
How can I solve this task?
Upvotes: 1
Views: 1133
Reputation: 35525
The following works:
my_table.col_3 = my_cell';
% or maybe you prefer
my_table.col_3 = cell2mat(my_cell)';
Let's analyze your problems:
Your sizes are wrong, you just need to transpose the input, from a row to a column!
As it says, you can not directly convert from cell to something else implicitly. cell2mat
is a way of doing it.
There is no such thing as my_table.col_3.Properties
so MATLAB gets confused and thinks you are doing something else with that dot .
.
Upvotes: 1
Reputation: 10792
If you want to keep the cell
type you could use:
my_table.col_3 = my_cell.'
Advantage: You can store more than one character in each row.
Why my_table.col_3 = my_cell
doesn't work:
%size(my_table.col_3) = 5x1
% ↕ ↕
%size(my_cell) = 1x5
As you can see above, the size of the first dimension of your cell array does not match with the size of the first dimension of you table. So you can simply permute the dimension of your cell with .'
So now:
%size(my_table.col_3) = 5x1
% ↕ ↕
%size(my_cell.') = 5x1
And matlab (and you) is/are happy.
Upvotes: 2