Search code examples
matlabstructdoublematlab-struct

Convert struct to double type in Matlab


Glcm (feature extraction method) give me an output in 'struct' type, while i need the output in 'double' type. I need a 'double' type as the input variable for the next step.

enter image description here

So, I've tried to convert it using several code showed below.

[gl] = glcm (B);
[gl] = struct2cell (gl);
[gl] = cell2mat (gl);
[fetrain] = double (gl);

The code give me an output but it's in 'complex double' type.

enter image description here

Is there a better way to convert 'struct' to 'double' type?

Or to convert 'complex double' to 'double' type?

Any help and suggestion would be very appreciated. Thank you.


Solution

  • First of all, rather than first converting to a cell and then to a matrix, you can convert directly from a struct to a double using struct2array.

    fetrain = struct2array(gl);
    

    That aside, there is no difference between a "complex double" and a double. They are both of type double.

    class(1i)
    % double
    

    You can use real to get the real component of the complex number or abs if you need the magnitude of it.

    real(1+1i)
    %   1
    
    abs(1+1i)
    %   1.4142
    

    In your case this would be:

    fetrain_real = real(fetrain);
    fetrain_mag = abs(fetrain);
    

    Update

    By default struct2array concatenates the data horizontally. If you want your data to be a matrix that is nFields x nData, then you could do something like the following:

    fetrain = struct2array(gl);
    
    % Reshape to be nFields x nData
    fetrain = permute(reshape(fetrain, [], numel(fieldnames(gl)), numel(gl)), [2 1 3]);