Search code examples
arraysmatlabcell

How to convert matrix to structure with following output


How to convert matrix A into structure B with field x, so that following output can be obtained.

    A=[2 3 4; 5 1 8; 4 4 6; 7 3 9] %input matrix

%desired output
B(1).x=[2,3,4]
B(2).x=[5,1,8]
B(3).x=[4,4,6]
B(4).x=[7,3,9] 

A is actually large matrix and I want to avoid "for" loop.


Solution

  • First use num2cell to convert A to a cell array where each cell contains one row of A. Then use cell2struct to obtain your result.

    Bcell = num2cell(A, 2);  %
    B = cell2struct(Bcell, 'x', size(A,2));
    

    % Thanks to Will for suggesting num2cell in place of mat2cell.