3

过去,我一直在广泛使用 Matlab 的table类。这个非常简单的代码,在脚本内或提示符下,按预期工作:

varNames = {'Date_time', 'Concentration_1', 'Concentration_2'};
testTable = array2table(zeros(5,3), 'VariableNames', varNames)

现在,我拥有与a相同table的.propertyhandle class

classdef TestClass < handle
    properties
        testTable (:,3) table
    end
    methods
        function testMethod(obj)
            varNames = {'Date_time', 'Concentration_1', 'Concentration_2'};
            obj.testTable = array2table(zeros(5,3), 'VariableNames', varNames);
            obj.testTable.Properties.VariableNames
        end
    end
end

如果我在命令提示符下执行以下命令,则将zeros其分配给table,但VariableNames保留其默认值,即{'Var1', 'Var2'}等。

tc = TestClass; tc.testMethod

甚至tc.testTable.Properties.VariableNames = varNames不会改变它们。

这是一个错误,还是我错过了什么?(我正在使用 Matlab R2017b)

4

1 回答 1

4

这似乎是 MATLAB 的属性 size validation的一个错误,因为当它被删除时,该行为会消失:

classdef SOcode < handle
    properties
        testTable(:,3) = table(1, 2, 3, 'VariableNames', {'a', 'b', 'c'});
    end
end

>> asdf.testTable

ans =

  1×3 table

    Var1    Var2    Var3
    ____    ____    ____

    1       2       3

对比

classdef SOcode < handle
    properties
        testTable = table(1, 2, 3, 'VariableNames', {'a', 'b', 'c'});
    end
end

>> asdf.testTable

ans =

  1×3 table

    a    b    c
    _    _    _

    1    2    3

在 TMW 解决错误之前,可以使用自定义验证函数来解决此问题,以保留所需的行为:

classdef SOcode < handle
    properties
        testTable table {TheEnforcer(testTable)}
    end
    methods
        function testMethod(obj)
            varNames = {'Date_time', 'Concentration_1', 'Concentration_2', 'hi'};
            obj.testTable = array2table(zeros(5,4), 'VariableNames', varNames);
            obj.testTable.Properties.VariableNames
        end
    end
end

function TheEnforcer(inT)
ncolumns = 3;
if ~isempty(inT)
    if size(inT, 2) ~= ncolumns
        error('An Error')
    end
end
end
于 2018-01-24T15:21:29.330 回答