Search code examples
matlabexport-to-excelmatlab-struct

Exporting a Matlab Variable Struct having multi dimension values to Excel


I have the following MATLAB struct with two fields:

enter image description here

I am trying to export this to Excel in two columns (or to notepad having just the second column of objectBoundingBoxes). When the field dimensions are 2x4 or 1x4, it displays semi colon separated values (which is what I want), but when the dimension is 3x4 or higher (up to 6x4), it just writes 3x4 double instead of writing them as semi colon separated values. So now when I copy paste the columns to Excel, it just writes 3x4 double instead of values.

Is there any way of displaying the semi colon separated values instead of 3x4 double in the variable display window of Matlab? If not then can you please suggest another way of exporting these values as [1,2,3,4; 5,6,7,8; 9,0,1,2....].


Solution

  • What you can do is use struct2cell to convert it to a 2D cell array and then you can convert the second column (the objectBoundingBoxes field) to a string using mat2str which will convert the matrix to a string. You should then be able to copy the result into Excel

    % Create some pseudo-data to test
    your_struct = struct('imageFilename', {'file1', 'file2', 'file3'}, ...
                         'objectBoundingBox', {1, rand(4,2), 2});
    
    % Convert your struct into an N x 2 cell array
    C = squeeze(struct2cell(your_struct)).';
    
    % Convert the second column to strings which represent the matrices
    C(:,2) = cellfun(@mat2str, C(:,2), 'UniformOutput', false);