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?
20 ビュー (過去 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!