2

测试matlab2015a。我正在使用一个结构数组,在某些时候我将它转换为一个带有struct2table. 这给出了一个很好的表,其中的列被命名为结构的字段。

一段时间后,由于不相关的原因,这些结构现在是类(或对象,不确定 matlab 中的标准命名)。struct2table拒绝它;直接应用table(objarray)会给出一个单列表,每行一个对象。我似乎无法找到一个object2table做显而易见的事情......

我最接近的是struct2table(arrayfun(@struct, objarray)),这有点不雅,并且每个数组项都会发出警告。那么,有什么更好的想法吗?

编辑:示例如下

>> a.x=1; a.y=2; b.x=3; b.y=4;
>> struct2table([a;b])

ans = 

x    y
_    _

1    2
3    4

这是原始的和期望的行为。现在创建一个包含内容的文件 ab.m

classdef ab; properties; x; y; end end

并执行

>> a=ab; a.x=1; a.y=2; b=ab; b.x=3; b.y=4;

试图在没有奥术咒语的情况下获得一张桌子会给你:

>> table([a;b])

ans = 

  Var1  
________

[1x1 ab]
[1x1 ab]

>> struct2table([a;b])
Error using struct2table (line 26)
S must be a scalar structure, or a structure array with one column
or one row.

>> object2table([a;b])
Undefined function or variable 'object2table'.

解决方法:

>> struct2table(arrayfun(@struct, [a;b]))
Warning: Calling STRUCT on an object prevents the object from hiding
its implementation details and should thus be avoided. Use DISP or
DISPLAY to see the visible public details of an object. See 'help
struct' for more information. 
Warning: Calling STRUCT on an object prevents the object from hiding
its implementation details and should thus be avoided. Use DISP or
DISPLAY to see the visible public details of an object. See 'help
struct' for more information. 

ans = 

x    y
_    _

1    2
3    4
4

1 回答 1

1

阅读您的问题,我不确定您是否真的应该将对象转换为表格。桌子有什么好处吗?

尽管如此,您的使用struct方法基本上是正确的。我会以一种易于使用且不显示警告的方式包装它。

将功能包装在一个类中:

classdef tableconvertible; 
    methods
        function t=table(obj)
            w=warning('off','MATLAB:structOnObject');
            t=struct2table(arrayfun(@struct, obj));
            warning(w);
        end
    end 
end

并在你的课堂上使用它:

classdef ab<tableconvertible; properties; x; y; end end

用法:

table([a;b])
于 2016-01-12T00:03:20.110 回答