为矩阵列标题添加字符串行

Mac*_*ac. 0 matlab matrix

对于Matlab中的矩阵,是否可以为每列的名称添加一行?

例如,我有这个矩阵

I =

203   397   313   420   
269   638   338   642    
270   316   526   336   
291   553   372   550    
296   797   579   774  
Run Code Online (Sandbox Code Playgroud)

我想拥有

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   
Run Code Online (Sandbox Code Playgroud)

Wol*_*fie 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'})
Run Code Online (Sandbox Code Playgroud)

表

使用表时,可以按变量名访问列,如下所示:

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
Run Code Online (Sandbox Code Playgroud)

注意:根据文档,表格是在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)];
Run Code Online (Sandbox Code Playgroud)

细胞阵列