How to Reshape a Matrix into a Cell

20 views (last 30 days)
Cedric Attias
Cedric Attias on 15 Apr 2024 at 18:26
Answered: Star Strider on 15 Apr 2024 at 19:19
I have a 821x9 matrix, which corresponsed to 821 time steps with all 9 entries of a 3x3 rotation matrix, in the formatting as follows:
timestep 1, R11 R12 R13 R21 R22 R23 R31 R32 R33
timestep 2, R11 R12 R13 R21 R22 R23 R31 R32 R33
etc...
timestep 821, R11 R12 R13 R21 R22 R23 R31 R32 R33
I want to convert this to a cell, so that I can have each timestep corresond to a single 3x3 rotation matrix.
In the end I want 821 cell entries, each containing a 3x3 rotation matrix like this:
cell entry 1, R11 R12 R13
R21 R22 R23
R31 R32 R33
cell entry 2, R11 R12 R13
R21 R22 R23
R31 R32 R33
etc...
cell entre 821, R11 R12 R13
R21 R22 R23
R31 R32 R33
I have tried using num2cell but have not been successful! Please help me.

Answers (2)

Voss
Voss on 15 Apr 2024 at 19:12
% 821x9 matrix (filled with integers for illustration)
M = reshape(1:821*9,9,[]).'
M = 821x9
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
% convert to the required cell array
C = num2cell(permute(reshape(M.',3,3,[]),[2 1 3]),[1 2]);
% check the first few entries
C{1}
ans = 3x3
1 2 3 4 5 6 7 8 9
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
C{2}
ans = 3x3
10 11 12 13 14 15 16 17 18
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
C{3}
ans = 3x3
19 20 21 22 23 24 25 26 27
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>

Star Strider
Star Strider on 15 Apr 2024 at 19:19
Transpose the row vector, call reshape, then transpose that result —
syms R11 R12 R13 R21 R22 R23 R31 R32 R33
k = 1;
timestep(k,:) = [R11 R12 R13 R21 R22 R23 R31 R32 R33]
timestep = 
cell{k} = reshape(timestep(k,:).', 3, []).'
cell = 1x1 cell array
{3x3 sym}
cell{k}
ans = 
I did it in the Symbolic Math Toolbos here for effect. Use the same code with your data for each value of ‘timestep’.
Also, subscript the results rather than creating separate variables.
.

Products


Release

R2023b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!