Adding a Column to a Table
1.559 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
John
el 6 de Oct. de 2023
Comentada: Walter Roberson
el 22 de Jul. de 2024
Hello everyone, I've just started out with Matlab for uni and am trying to add a column to a table. I ran into the following error message
Error using .
To assign to or create a variable in a table, the number of rows must match the height of the table.
My code is written below:
%Creates a table called 'tab' using the data in the coronavirus-cases.csv
%file.
tab = readtable("coronavirus-cases.csv");
%Creates a row of zeros with the same height as tab.
newTabCol = zeros(height(tab), 1);
%Adds the column and titles it "Seven Day Average".
tab.newTabCol = "Seven Day Average";
What confuses me is that the height of newTabCol matches tab. Both have 153772 rows:
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1503904/image.png)
I'm sure I'm missing something basic but any help would be appreciated.
Kind regards,
John
0 comentarios
Respuesta aceptada
Dyuman Joshi
el 6 de Oct. de 2023
The variable name/title should be used after using the dot notation inside parenthesis and the data to append should be on the right side of the equation.
%Creates a row of zeros with the same height as tab.
newTabCol = zeros(height(tab), 1);
%Adds the column and titles it "Seven Day Average".
tab.("Seven Day Average") = newTabCol;
2 comentarios
Dyuman Joshi
el 6 de Oct. de 2023
You are welcome!
Also, do check out Image Analst's suggestion as well.
Más respuestas (1)
Image Analyst
el 6 de Oct. de 2023
To add a column to a table, use addvars
help addvars
2 comentarios
Alessandro Livi
el 22 de Jul. de 2024
Editada: Walter Roberson
el 22 de Jul. de 2024
I read all that, tried it and it didn't work (or I hadn't rotated the vector yet with ' )
What did work is
A = zeros([1 size(app.StimInputTable.Data,1)]);
app.StimInputTable.Data.Var4 = A';
I suppose that
A = zeros([1 size(app.StimInputTable.Data,1)]);
app.StimInputTable.Data = ADDVARS(app.StimInputTable.Data, A');
might also work if I get all the app.'s and .Data's and A' in the right place but noone explains about rotating the vector to a column in the Help or in answers copied from Help.
Walter Roberson
el 22 de Jul. de 2024
T = array2table([10 9 8])
T.GHI = [1 2 3 4]
The key here is that the variable to be added might legitimately have multiple columns, so the process of adding a variable cannot automatically flip vectors -- it might be the wrong thing to do.
Ver también
Categorías
Más información sobre Tables en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!