matlab cell 與高維矩陣之間的轉換

MATLAB cell 與 matrix 之間的轉換

本文記錄了Shecan在研究中遇到的Cell與matrix相互轉換的問題。cell2mat可以轉換比較簡單的cell類型,但是如果複雜一些,需要用cat和reshape,permute相結合。

Example 1

cell2mat 可以實現簡單的cell到矩陣的拼接,如
{[1],[2];[3],[4]} \{[1],[2];[3],[4]\}
變成
[1234] \left[ \begin{matrix} 1 & 2 \\ 3 & 4 \end{matrix} \right]

A = cell(2);
A{1,1} = 1; 
A{1,2} = 2;
A{2,1} = 3;
A{2,2} = 4;
B = cell2mat(A)

Example 2

輸入:
A={[2222],[1111]} A = \left\{ \begin{matrix}\left[ \begin{matrix} 2 & 2 \\ 2 & 2 \end{matrix} \right],\left[ \begin{matrix} 1 & 1 \\ 1 & 1 \end{matrix} \right]\end{matrix}\right\}

A = cell(1,2);
A{1,1} = [2,2;2,2];
A{1,2} = [1,1;1,1];

輸出:

cat(1,mat) 表示按列拼接, cat(2,mat)表示按行拼接,cat(3,mat)表示按第三個維度拼接。

B = cat(3,A{:});

B(:,:,1)=[2222]B(:,:,2)=[1111] B(:,:,1) = \left[ \begin{matrix} 2 & 2 \\ 2 & 2 \end{matrix} \right]\\B(:,:,2) = \left[ \begin{matrix} 1 & 1 \\ 1 & 1 \end{matrix} \right]

Example 3

輸入:
{[21][21][21][21]} \left\{ \begin{matrix} \left[ \begin{matrix} 2 \\ 1 \end{matrix} \right] & \left[ \begin{matrix} 2 \\ 1 \end{matrix} \right]\\ \left[ \begin{matrix} 2 \\ 1 \end{matrix} \right] & \left[ \begin{matrix} 2 \\ 1 \end{matrix} \right]\end{matrix}\right\}

A = cell(2,2);
A{1,1} = [2;1]; 
A{1,2} = [2;1];
A{2,1} = [2;1];
A{2,2} = [2;1];

輸出:

A = 2×2 cell 數組
    {2×1 double}    {2×1 double}
    {2×1 double}    {2×1 double}

目標: 把 A 轉換成以下的矩陣B
B(:,:,1)=[2222]B(:,:,2)=[1111] B(:,:,1) = \left[ \begin{matrix} 2 & 2 \\ 2 & 2 \end{matrix} \right]\\B(:,:,2) = \left[ \begin{matrix} 1 & 1 \\ 1 & 1 \end{matrix} \right]

$$

$$

B = cat(2,A{:})

% cat(1,mat) 表示按列拼接, cat(2,mat)表示按行拼接,cat(3,mat)表示按第三個維度拼接。

輸出:

B = 2×4
     2     2     2     2
     1     1     1     1

以上的矩陣轉置後reshape便可以的到需要的矩陣。reshape矩陣變換的優先方向是列-行-第三維度。

輸入:

reshape(B',[2,2,2])

輸出:

ans = 
ans(:,:,1) =

     2     2
     2     2


ans(:,:,2) =

     1     1
     1     1

Alternatively, reshape based on columns. 如此,需要多費一番周折,最後需要一個高維矩陣轉置。這樣做的有點是當矩陣大於三維的時候比較容易理解和思考。

輸入:

B = cat(1,A{:})

輸出:因爲這裏是按列拼接

B = 8×1
     2
     1
     2
     1
     2
     1
     2
     1

同樣,reshape成三維矩陣。

輸入:

B=reshape(B,[2,2,2])

輸出:得到這樣的結果是因爲reshape是先放到列,再放到行,最後放到第三維度。這個和MATLAB矩陣存儲方式有關,列優先。

B = 
B(:,:,1) =

     2     2
     1     1


B(:,:,2) =

     2     2
     1     1

最後做一個一三維度的裝置即可。

輸入:

permute(B,[3,2,1])

即可以得到所需要的矩陣。

結束語:寥寥記下幾筆。說到cell,必須要在這裏感謝一下昔日的老友,從他的程序裏學來的,然後越用越順手。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章