Reshape a row vector and convert it to a cell array

I have a row vector as the following:
x = [1:10, 101:110, 11:20, 111:120]
Now I want to convert it to a 2-by-2 cell array C, where
C(1,1) = {[1:10]}
C(1,2) = {[11:20]}
C(2,1) = {[101:110]}
C(2,2) = {[111:120]}
How can I achieve this?

回答 (2 件)

Chunru
Chunru 2021 年 11 月 16 日

1 投票

x = [1:10, 101:110, 11:20, 111:120];
x = reshape(x, [20, 2])';
C = mat2cell(x, [1 1], [10 10])'
C = 2×2 cell array
{[ 1 2 3 4 5 6 7 8 9 10]} {[ 11 12 13 14 15 16 17 18 19 20]} {[101 102 103 104 105 106 107 108 109 110]} {[111 112 113 114 115 116 117 118 119 120]}
Image Analyst
Image Analyst 2021 年 11 月 16 日

1 投票

Why do you want to do that?? That kind of situation does not call for a slow and inefficient cell array. You could simply use a 2-D double array:
C = reshape(x, [], 10);
Cell arrays are used for situations like where the arrays in each cell are not all of the same size. See the FAQ:

4 件のコメント

Chunru
Chunru 2021 年 11 月 16 日
x = [1:10, 101:110, 11:20, 111:120];
C = reshape(x, [], 10)
C = 4×10
1 5 9 103 107 11 15 19 113 117 2 6 10 104 108 12 16 20 114 118 3 7 101 105 109 13 17 111 115 119 4 8 102 106 110 14 18 112 116 120
Image Analyst
Image Analyst 2021 年 11 月 16 日
@Chunru, thanks for trying it and discovering my coding error. Corrected code is below:
x = [1:10, 101:110, 11:20, 111:120]
x = 1×40
1 2 3 4 5 6 7 8 9 10 101 102 103 104 105 106 107 108 109 110 11 12 13 14 15 16 17 18 19 20
C = reshape(x, 10, [])'
C = 4×10
1 2 3 4 5 6 7 8 9 10 101 102 103 104 105 106 107 108 109 110 11 12 13 14 15 16 17 18 19 20 111 112 113 114 115 116 117 118 119 120
hmhuang
hmhuang 2021 年 11 月 16 日
@Image Analyst May I ask how to make x = [1:10, 101:110, 11:20, 111:120] to be x = [1:10, 11:20; 101:110, 111:120] by using reshape or some MATLAB built-in function?
Image Analyst
Image Analyst 2021 年 11 月 16 日
@hmhuang, for that, try this:
x = [1:10, 101:110, 11:20, 111:120];
C = reshape(x, 10, [])';
Codd = C(1:2:end,:);
Ceven = C(2:2:end,:);
Codd = reshape(Codd', 20, [])';
Ceven = reshape(Ceven', 20, [])';
x = [Codd; Ceven]
x = 2×20
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
Why do you need to do this rearrangement anyway?

サインインしてコメントする。

カテゴリ

ヘルプ センター および File ExchangeOperators and Elementary Operations についてさらに検索

タグ

質問済み:

2021 年 11 月 16 日

コメント済み:

2021 年 11 月 16 日

Community Treasure Hunt

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

Start Hunting!

Translated by