I am having trouble understanding this error "To assign to or create a variable in a table, the number of rows must match the height of the table.", can someone explain?
46 次查看(过去 30 天)
显示 更早的评论
As stated in the title, I'm struggling with getting rid of error message "To assign to or create a variable in a table, the number of rows must match the height of the table."
Here is a snippit of my original code. The line specifically causing hte probled is the line within the For loop. Sorry if this is a simple question, I do not usually work MATLAB and got thrown into this project. Thank you!
units_tbl(1,:)
values_tbl_new = vertcat(units_tbl(1,:),values_tbl);
for k = 1:length(vars_wanted)
values_tbl_new.(vars_wanted(k)) = values_tbl.(vars_wanted(k));
end
1 个评论
Stephen23
2024-7-31
编辑:Stephen23
2024-7-31
"I am having trouble understanding this error "To assign to or create a variable in a table, the number of rows must match the height of the table.", can someone explain?"
Here is a table with three rows:
T = array2table(randi(9,3,4))
Creating a new column/variable which also has three rows will work correctly:
T.('new') = [1;99;Inf]
Creating a new column/variable which does not have three rows will fail:
T.('bad') = [1;2;3;4;5;6]
回答(1 个)
Cris LaPierre
2024-7-31
Values_tbl_new has n+1 rows because you vertically concatenate the first row of units_tbl to values_tbl.
You then try to assign one column (or variable) of table values_tbl to a colum (or variable) of values_tbl_new. The number of rows differ between these two tables by 1, hence the error.
I would suggest not placing your units in the first row. Instead, add it to the table properties. The VariableUnits one would make sense to me.
That might look like this.
values_tbl_new = table();
values_tbl_nes.Properties.VariableUnits = units_tbl(1,:);
for k = 1:length(vars_wanted)
values_tbl_new.(vars_wanted(k)) = values_tbl.(vars_wanted(k));
end
2 个评论
Cris LaPierre
2024-7-31
Here's an example of how I would do it.
values_tbl = readtable('patients.xls')
vars_wanted = ["Height" "Weight" "Smoker"];
values_tbl_new = values_tbl(:,ismember(values_tbl.Properties.VariableNames,vars_wanted))
Steven Lord
2024-7-31
Or even simpler, skip the ismember call and the direct request for the variable names from the table property. Just use indexing.
values_tbl = readtable('patients.xls');
head(values_tbl) % Show just the first few rows
vars_wanted = ["Height" "Weight" "Smoker"];
values_tbl_new = values_tbl(:, vars_wanted); % Indexing using variable names
head(values_tbl_new) % Show just the first few rows
See the "Index by Variable Names" section on this documentation page. The table at the end of that documentation page describes other techniques / syntaxes to access data in a table.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!