是否可以为Matlab中的矩阵添加每列名称的行?
例如我有这个矩阵
I =
203 397 313 420
269 638 338 642
270 316 526 336
291 553 372 550
296 797 579 774
我想
I =
X Y Z weight
203 397 313 420
269 638 338 642
270 316 526 336
291 553 372 550
296 797 579 774
答案 0 :(得分:6)
对于矩阵:没有。所有矩阵元素都必须是数字。
Tables
是最好的选择,因为你可以保持数据的数字格式化(像矩阵那样进行交互),但有标题......
% Set up matrix
I = [203 397 313 420
269 638 338 642
270 316 526 336
291 553 372 550
296 797 579 774];
% Convert to table
array2table(I, 'VariableNames', {'X', 'Y', 'Z', 'weight'})
使用表时,您可以按其变量名访问列,如下所示:
disp(I.X) % Prints out the array in the first column
disp(I(:,1)) % Exactly the same result, but includes the column heading
% For operations, reference the variables by name
s = I(:,1) + I(:,2); % Gives error
s = I.X + I.Y; % Gives expected result
注意:根据文档,表格是在R2013b中引入的,如果您有旧版本的Matlab,则必须使用单元格数组...
% Set up matrix as before
I = [203 397 313 420
... ... ... ...];
% Convert to cell and add header row
I = [{'X', 'Y', 'Z', 'weight'}; num2cell(I)];
答案 1 :(得分:1)
使用table
:
X = [203, 269, 270, 291, 296];
Y = [397, 638, 316, 553, 797];
Z = [313, 338, 526, 372, 579];
weight = [420, 642, 336, 550, 774];
T = table(X, Y, Z, weight);
结果如下:
>> T
T =
X Y Z weight
____________ ____________ ____________ ____________
[1x5 double] [1x5 double] [1x5 double] [1x5 double]