array splits into more variables when reading from table

I have a problem with creating the same table as I write, if one of the variables is an array.
I have this:
T= {[1,2,3], 10, 20, 30, 'string'};
T = array2table(T,'VariableNames',{'positions' 'length' 'height' 'depth' 'name'});
writetable(T,file1.csv,'Delimiter',' ');
Then I read the file with:
data=readtable(file1.txt,'Delimiter',' ');
Then I want to assign the data to its respective variables.
positions=data.positions;
length=data.beamLength;
height=data.loadPositions;
depth=data.loadForces;
name=data.beamSupport;
The problem is that when there is an array, the variable splits into more variables. for example, the positions variable splits into positions_1, positions_2, positions_3.
I get an error saying that positions is undefined, because now the array isn't under 1 variable called positions. I need to assign the array. if positions is 1 value there is no problem.
I have tried with cell2mat, table, many things but it just won't work.

回答(1 个)

This is documented behavior of writetable. Can you not simply combine them back after reading? For example:
data.Positions = [data.Positions_1 data.Positions_2 data.Positions_3];
data.Positions_1 = []; % remove single columns
data.Positions_2 = [];
data.Positions_3 = [];

2 个评论

The problem is that the size of the array can vary, its not always 3 it should work no matter how big it is. The whole array should be assigned to the positions variable, with the square brackets.
It would not be hard to find all the variables named 'Positions_n" using strcmp on the VariableNames property, group them into one variable in the table, and delete the rest using something like
t(:,varsToDelete) = [];
Hope this helps.

此问题已关闭。

关闭:

2021-8-20

Community Treasure Hunt

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

Start Hunting!

Translated by