Subscripted assignment dimension mismatch for table variable

6 views (last 30 days)
I want to initialize a table with 4 empty rows and replace each row one by one. The first variable is string, and others are numerical. But an error pops up as: "Subscripted assignment dimension mismatch for table variable 'f1'".
t1 = struct('f1','001','f2',2,'f3',3,'f4',4);
t2 = cell2table(cell(4,4),'VariableNames',{'f1','f2','f3','f4'});
t2(1,:) = struct2table(t1);

Answers (3)

Peter Perkins
Peter Perkins on 25 Jul 2017
t2 is a cable all of whose variables are cell arrays. That's almost certainly not what you want.
Assigning one row at a time is sometimes not the best way to create a table, but if you really need to do that, you probably want to preallocate both the size and the data types of the table's variables, and then assign each row.
>> t = table(cell(4,1),NaN(4,1),NaN(4,1),NaN(4,1),'VariableNames',{'f1','f2','f3','f4'})
t =
4×4 table
f1 f2 f3 f4
__ ___ ___ ___
[] NaN NaN NaN
[] NaN NaN NaN
[] NaN NaN NaN
[] NaN NaN NaN
>> t(1,:) = {'001' 2 3 4}
t =
4×4 table
f1 f2 f3 f4
_____ ___ ___ ___
'001' 2 3 4
[] NaN NaN NaN
[] NaN NaN NaN
[] NaN NaN NaN
>> t(2,:) = {'002' 5 6 7}
t =
4×4 table
f1 f2 f3 f4
_____ ___ ___ ___
'001' 2 3 4
'002' 5 6 7
[] NaN NaN NaN
[] NaN NaN NaN
Note the right-hand side of those assignments. Normally, if the LHS is a parenthesis subscript expression, the RHS needs to be the same type, a table in this case. But table providea a conveneince where a RHS that's a cell array is treated as if cell2table were called on it. Because you have mixed types in each row, that's helpful.

Walter Roberson
Walter Roberson on 25 Jul 2017
In t1 put your quoted strings in {}. As they are now they are vectors that you are trying to store in a scalar location

Andrei Bobrov
Andrei Bobrov on 25 Jul 2017
t1 = struct('f1','001','f2',2,'f3',3,'f4',4);
t2 = cell2table(cell(4,4),'VariableNames',{'f1','f2','f3','f4'});
t2{1,:} = struct2cell(t1)';

Categories

Find more on Tables in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!