與表工作,如果你想自動生成變量LastName
,Sex
,Age
等,您可以:
- 獲取變量的名稱:它們存儲在表
的
Properties.VariableNames
屬性中
- 然後id entify它們號碼作爲varaible列表的長度
- 遍歷表列(所述varaibles)來訪問所述數據
現在的問題在於在創建單個varaibles的在其中的名稱的將數據存儲在工作區中。
您可以通過將數據存儲在允許動態生成字段名稱的struct
中解決此問題。
因此,您可以在表格中的變量名稱後面生成字段的名稱。
一種可能實現該方法的colud是:
% Load the data
load hospital
% Convert dataset to table
T = dataset2table(hospital)
% Get the name of the varaibles
var_names=T.Properties.VariableNames
% Identify the number of varaibles (to be used in the next loop)
n_var=length(var_names)
% Store the data in a struct
% Get the name of the rows
hospital_data.row_names=T.Properties.RowNames;
% Loop over the variables
% Create dynamically the names of the fields of the struct after the name
% of the variables
for i=1:n_var
hospital_data.(var_names{i})=T{:,i}
end
這產生一個struct
名爲hospital_data
其字段是:
hospital_data =
row_names: {100x1 cell}
LastName: {100x1 cell}
Sex: [100x1 nominal]
Age: [100x1 double]
Weight: [100x1 double]
Smoker: [100x1 logical]
BloodPressure: [100x2 double]
Trials: {100x1 cell}
希望這有助於
Qapla」