Subscripted assignment dimension mismatch for table variable
4 次查看(过去 30 天)
显示 更早的评论
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);
0 个评论
回答(3 个)
Peter Perkins
2017-7-25
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
2017-7-25
In t1 put your quoted strings in {}. As they are now they are vectors that you are trying to store in a scalar location
0 个评论
Andrei Bobrov
2017-7-25
t1 = struct('f1','001','f2',2,'f3',3,'f4',4);
t2 = cell2table(cell(4,4),'VariableNames',{'f1','f2','f3','f4'});
t2{1,:} = struct2cell(t1)';
0 个评论
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!