【问题标题】:Add a string row for matrix column headings为矩阵列标题添加字符串行
【发布时间】:2017-05-03 12:43:37
【问题描述】:

是否可以在 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   

【问题讨论】:

标签: matlab matrix


【解决方案1】:

对于矩阵:不。所有矩阵元素必须是数字。

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)];

【讨论】:

  • 谢谢,我应用了你的第一个想法 :-)
【解决方案2】:

使用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]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-06
    • 2011-10-28
    • 2020-05-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多