How to unnest a cell array with nested data and text content if the row and column dimensions do not agree with each other in MATLAB Rb2020?

Viewed 107

I have a (72x1 cell) which content is defined by the following block/section:

          COLUMN1
ROW1      Text Nr.1
ROW2      2345x3 double
ROW3      Text Nr.2

....times 24 to get the mentioned 72x1 cell array

My goal now is to unnest the 2345x3 double contents in a way, that I obtain the following data order:

                     COLUMN1             COLUMN2        COLUMN3
                     Text Nr.1          (empty)         (empty)
                      value 1            value 1        value 1
                      value 2            value 2        value 2
                      value 3            value 3        value 3
                      value 4            value 4        value 4
                      value 5            value 5        value 5
                      value 6            value 6        value 6
                      value 7            value 7        value 7
                       etc.               etc.           etc.
                      Text Nr.2           (empty)       (empty)
                      Text Nr.1           (empty)       (empty)
                       value 1            value 1        value 1
                       value 2            value 2        value 2
                       value 3            value 3        value 3
                       value 4            value 4        value 4
                       value 5            value 5        value 5
                       value 6            value 6        value 6
                       value 7            value 7        value 7
                       etc.               etc.           etc.
                       Text Nr.2          (empty)        (empty)

I would like to use a for loop for this, in case the amount of rows changes. However I am uncertain how to approach this problem even? (reshape, cellfun?)

That why I would like to ask you if you have a code in mind?

Note: I need this data structure for a macro which generates geometrical structures in CAD programms

1 Answers

You can use something like this:

x={'lorem';[1 2 3;4 5 6;7 8 9;2344*3+1 2344*3+2 2344*3+3];'ipsum'; ...
   'dolor';-[1 2 3;4 5 6;7 8 9;2344*3+1 2344*3+2 2344*3+3];'sit amet'};

m={};
for i=1:floor(numel(x)/3) %ignore trailing garbage (incomplete entry)
  k=x{3*(i-1)+2};
  m=[ m ; ...
      x(3*(i-1)+1) cell([1 size(k,2)-1]) ; ...
      mat2cell( k, ones([size(k,1) 1]), ones([size(k,2) 1]) ) ; ...
      x(3*(i-1)+3) cell([1 size(k,2)-1]) ];
end

Since the for-loop only performs 24 iterations in your use case, I believe this approach should be fairly efficient.

Related