0

我正在尝试在表格末尾添加行。例如:

LastName = {'Smith';'Johnson';'Williams';'Jones';'Brown'};
Age = [38;43;38;40;49];
Height = [71;69;64;67;64];
Weight = [176;163;131;133;119];
BloodPressure = [124 93; 109 77; 125 83; 117 75; 122 80];
Tab=table;
s=struct;
for i=1:5
    s.name=LastName{i};
    s.age=Age(i);
    s.heigt=Height(i);
    s.weight=Weight(i);
    s.BP=BloodPressure(i);
    temp=struct2table(s);
    Tab(end+1,:)=temp;
end

该表被声明为空,它添加了第一行,但在 for 循环的第二次迭代中给出了以下错误消息:

Subscripted assignment dimension mismatch for table variable 'name'.

我知道发生这种情况是因为变量名称在第二次迭代中有更多字符。有什么方法可以实现吗?

这是我生成的用于解释我的问题的示例代码。在我的实际代码中,问题类似,但结构类型变量是从我无法修改的不同函数返回的。

4

1 回答 1

3

首先定义整个结构体数组:

LastName = {'Smith';'Johnson';'Williams';'Jones';'Brown'};
Age = [38;43;38;40;49];
Height = [71;69;64;67;64];
Weight = [176;163;131;133;119];
BloodPressure = [124 93; 109 77; 125 83; 117 75; 122 80];
s = struct('name',LastName,'age',num2cell(Age),...
    'heigt',num2cell(Height),...
    'weight',num2cell(Weight),...
    'BP',num2cell(BloodPressure,2));

然后将其转换为表格:

Tab = struct2table(s);

结果:

Tab = 
       name       age    heigt    weight        BP    
    __________    ___    _____    ______    __________
    'Smith'       38     71       176       124     93
    'Johnson'     43     69       163       109     77
    'Williams'    38     64       131       125     83
    'Jones'       40     67       133       117     75
    'Brown'       49     64       119       122     80
于 2016-08-01T19:06:30.430 回答