我已将一个X
充满数据的矩阵及其每列的相应标题导入 MATLAB。现在的问题是如何X
在标题单元格中按相应名称重命名每一列。
我想循环执行此操作。
谁能告诉我在这种情况下如何循环重命名程序?
2 回答
I suggest creating a structure out of the data, rather than individual variables. Even with a large number of columns, this will not clutter the workspace, nor will it overwrite variables already in the workspace in the case of a name collision. It will keep all the data from the spreadsheet together, and still allowing access to it by column name. To easily create a structure from a cell array of column names and a matrix of data, use cell2struct:
>> colnames = {'odds','evens'};
>> data = [1 2;3 4;5 6];
>> spreadsheet_structure = cell2struct(num2cell(data,1), colnames, 2)
spreadsheet_structure =
odds: [3x1 double]
evens: [3x1 double]
(num2cell(M,1)
creates a cell array in which each cell is a column from matrix M
)
遍历标题列并使用 eval 创建变量,其名称包含在矩阵“标题”中的字符串中:
[X,header,~] = xlsread('eaef21.xls',1,'A1:AY541');
for H = 1:size(header,2)
eval([header(1,H), " = X(:,", H, ");"]);
end
eval
此外,将上述内容替换为通常非常有用,disp
直到您对它按您想要的方式工作感到满意为止。使用disp
也将帮助您了解正在发生的事情。