Álex
Álex

Reputation: 1703

Matlab object array to table (or struct array)

Testing matlab2015a. I was using a struct array that at some point I converted to a table with struct2table. This gave a nice table with columns named as the fields of the struct.

Some time later and by unrelated reasons, these structs are now classes (or objects, not sure about the standard naming in matlab). struct2table rejects it; directly applying table(objarray) gives a one-column table with one object per row. I seem unable to find an object2table that does the obvious thing...

The closest I've come is struct2table(arrayfun(@struct, objarray)), which is a bit inelegant and spits a warning per array item. So, any nicer ideas?

Edit: example as follows

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

ans = 

x    y
_    _

1    2
3    4

This is the original and desired behavior. Now create a file ab.m with contents

classdef ab; properties; x; y; end end

and execute

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

trying to get a table without the arcane incantation gives you:

>> 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'.

And the workaround:

>> 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

Upvotes: 2

Views: 2100

Answers (1)

Daniel
Daniel

Reputation: 36710

Reading your question, I am not sure if you really should convert an object to a table. Is there any advantage of a table?

Nevertheless, your approach using struct is basically right. I would just wrap it in a way it's easy to use and does not display a warning.

Wrap the functionallity in a class:

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

And use it in your class:

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

Usage:

table([a;b])

Upvotes: 1

Related Questions