0
votes

I need to reshape a T1 = [1x5] cell array, where each cell is a [5x1] cell array of numbers into a S1 = [m-by-n] matrix of numbers. The problem is the initial cell array T1 may have different number of rows in each cell - meaning I don't have a square shaped array to use " cell2mat " function.

Example:

T1=[1x5] cell array
T1{1}   T1{2}   T1{3}   T1{4}   T1{5}
 1       2       3       4       5
 6       7       8       9      10
11      12      13      14      15
16      17      18      19      20
21      22      23      24

I need to add all of the columns together:

T2=
 1   2   3   4   5
 6   7   8   9  10
11  12  13  14  15
16  17  18  19  20
21  22  23  24

And then reshape the array into [m-by-n] array (always square shaped), in this example S1=[3x8]:

S1=
 1  2  3  4  5  6  7  8
 9 10 11 12 13 14 15 16
17 18 19 20 21 22 23 24

I thought that maybe I could reshape T1 into [x-by-1] array and then reshape that array in to S1=[m-by-n]. But what should i do in order to get results like this:

T3=
1
2
3
4
...
24

And not like

T3=
1
6
11
16
21
2
...
24

Any help would be appreciated.

1
Please add the code you developed so far.Irreducible
You need to come up with more specific shape criteria than "rectangular." Why 3 x 8 and not 4 x 6 or 2 x 12?excaza
Have you tried simply transposing T1? When you create an array, it always goes along the first dimension, so transposing should get you the result you are looking forRichard

1 Answers

1
votes

One strategy would be:

  1. Pad all of the cell array elements with NaN to make them the same size
  2. Concatenate the padded arrays
  3. Remove the NaNs
  4. Reshape

That would look like this...

% 1. Get maximum size of T elements
%    Pad all elements of T up to maxn values with NaN
maxn = max(cellfun( @numel, T ));
Tpadded = cellfun( @(x) [x; NaN(maxn-numel(x))], T, 'uni', 0);
% 2. Convert to array.
Tpadded = cat( 2, Tpadded{:} );
% 3. Reshape to be one row and remove NaNs
Trow = reshape( Tpadded.', 1, [] );
Trow = Trow(~isnan(Trow));
% 4. Reshape to desired result
Tout = reshape( Trow, 8, 3 ).';

Result

Tout = [1   2  3  4  5  6  7  8
        9  10 11 12 13 14 15 16
        17 18 19 20 21 22 23 24]