Search code examples
arraysmatlabstructuredata-conversion

Function to convert array of heterogeneous variables to structure (preserving name)


I want to write a function that converts a variable number of variables (in the example below the array sc, the matrix A, the number T) to a structure that contains them. The respective structure labels should be the names of the variables themselves. See example below:

sc=[1 2 1 0.5 0.01 0.03];
A=[1,2,3,4;1,2,3,4];
T=2;

I want my function to do this:

data.sc=sc;
data.A=A;
data.T=T;

so that the output is:

data =

struct with fields:

sc: [1 2 1 0.5000 0.0100 0.0300]
 A: [2×4 double]
 T: 2

for a variable number of heterogeneous arguments.


Solution

  • You can use the function inputname, in combination with dynamic field names.

    function outStruct =  dataStructifier(varargin)
        outStruct = struct;
        for k = 1:nargin
            outStruct.(inputname(k)) = varargin{k};
        end
    end
    

    This results in:

    sc=[1 2 1 0.5 0.01 0.03];
    A=[1,2,3,4;1,2,3,4];
    T=2;
    
    data = dataStructifier(sc, A, T)
    
    data = 
    
      struct with fields:
    
        sc: [1 2 1 0.5000 0.0100 0.0300]
         A: [2×4 double]
         T: 2
    

    Note that the function will cause an error when providing 'nameless variables', for example:

    data = dataStructifier(sc, A, T, ones(10))