unexpected response when trying to concatenate by row after accessing cell value

22 ビュー (過去 30 日間)
Thomas
Thomas 2024 年 11 月 26 日
編集済み: Stephen23 2024 年 11 月 26 日
I am trying to access the values in certain cells then concatenate the results together by row :
% initialise cell data for example
cells = cell(5, 1);
cells{1, 1} = [5 1];
cells{2, 1} = [4 1];
cells{3, 1} = [3 1];
cells{4, 1} = [2 1];
cells{5, 1} = [1 1];
% the code im trying to run
all_cells = [cells{1:5, 1};];
the result i get: 1x10 matrix [5,1,4,1,3,1,2,1,1,1]
what i am expecting to happen:
% my current workaround
cell_1=cells{1, 1};
cell_2=cells{2, 1};
cell_3=cells{3, 1};
cell_4=cells{4, 1};
cell_5=cells{5, 1};
y_folds = [cell_1; cell_2; cell_3; cell_4; cell_5;];
the result i expected: 5x2 matrix [5,1;4,1;3,1;2,1;1,1]
i also tried to use comma instead of semi-colon as such:
all_cells = [cells{1:5, 1},];
but i get the same result as with a semi-colon: 1x10 matrix [5,1,4,1,3,1,2,1,1,1]

採用された回答

Stephen23
Stephen23 2024 年 11 月 26 日
編集済み: Stephen23 2024 年 11 月 26 日
The MATLAB approach is to simply call VERTCAT instead of the concatenation operator:
C = {[5,1];[4 1];[3 1];[2 1];[1 1]};
M = vertcat(C{:})
M = 5×2
5 1 4 1 3 1 2 1 1 1
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
Explanation of how this works:
The trailing semi-colon or comma in your code attempts do nothing whatsoever.

その他の回答 (1 件)

Thomas
Thomas 2024 年 11 月 26 日
編集済み: Thomas 2024 年 11 月 26 日
this gives the correct answer
cells = cell(5, 1);
cells{1, 1} = [5 1];
cells{2, 1} = [4 1];
cells{3, 1} = [3 1];
cells{4, 1} = [2 1];
cells{5, 1} = [1 1];
all_cells = [cell2mat(cells(1:5, 1));];
the result: 5x2 matrix [5,1;4,1;3,1;2,1;1,1]

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

製品


リリース

R2024a

Community Treasure Hunt

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

Start Hunting!

Translated by