2017-02-26 109 views
0

在這個例子中:MATLAB - 根據其基礎數據類型將表拆分爲單個列數組?

load hospital 
T = dataset2table(hospital) 

我轉換爲表格,因爲我想,也許這將是更容易使用。但我並不在乎答案中的方法是否適用於數據集或表格。我想獲取每一列,例如「LastName」,「Sex」等,獲取其基礎數據類型,併爲每個列創建一個新變量。是否有一種方法可以在不迭代表格的情況下完成此操作(即內置函數)?至少如果我不能轉換爲其基礎類型,我可以將它們拆分成單獨的單元格數組嗎?

最終的結果將具有在工作空間中的變量這樣:

名字

性別

年齡

重量

吸菸者

血壓

試驗

回答

0

與表工作,如果你想自動生成變量LastNameSexAge等,您可以:

  • 獲取變量的名稱:它們存儲在表
  • 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」

相關問題