Swap shape of cell array full of arrays

3 ビュー (過去 30 日間)
Cedric Kotitschke
Cedric Kotitschke 2024 年 1 月 15 日
コメント済み: Cedric Kotitschke 2024 年 1 月 15 日
Hey,
I have a nxn cell array where each element contains a 1xm array.
How do I turn this into a 1xm cell array where each element contains a nxn array?
So basically from:
{[1 2 3 4 5], [1 2 3 4 5]; [1 2 3 4 5], [1 2 3 4 5]}
to
{[1 1; 1 1], [2 2; 2 2], [3 3; 3 3], [4 4; 4 4], [5 5; 5 5]}
Thanks!

採用された回答

Stephen23
Stephen23 2024 年 1 月 15 日
C = {[1,2,3,4,5], [1,2,3,4,5]; [1,2,3,4,5], [1,2,3,4,5]}
C = 2×2 cell array
{[1 2 3 4 5]} {[1 2 3 4 5]} {[1 2 3 4 5]} {[1 2 3 4 5]}
F = @(a)reshape(a,1,1,[]);
D = reshape(num2cell(cell2mat(cellfun(F,C,'uni',0)),1:2),size(C{1}))
D = 1×5 cell array
{2×2 double} {2×2 double} {2×2 double} {2×2 double} {2×2 double}
D{:}
ans = 2×2
1 1 1 1
ans = 2×2
2 2 2 2
ans = 2×2
3 3 3 3
ans = 2×2
4 4 4 4
ans = 2×2
5 5 5 5
  1 件のコメント
Cedric Kotitschke
Cedric Kotitschke 2024 年 1 月 15 日
That's elegant, thanks!

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

その他の回答 (1 件)

Hassaan
Hassaan 2024 年 1 月 15 日
編集済み: Hassaan 2024 年 1 月 15 日
Approach 1
% Example input: an nxn cell array
n = 2;
m = 4; % changed from 5 to 4 to make it reshapeable to 2x2
inputCellArray = cell(n, n);
for i = 1:n
for j = 1:n
inputCellArray{i, j} = 1:m; % changed from [1 2 3 4 5] to 1:4
end
end
% Reshape the input cell array into a 1xm cell array of 1x(n^2) arrays
reshapedCellArray = reshape(inputCellArray', 1, []);
% Use cellfun to reshape each element in the reshapedCellArray into a 2x2 array
outputCellArray = cellfun(@(x) reshape(x, n, []), reshapedCellArray, 'UniformOutput', false);
% Display the resulting 1xm cell array of nxn arrays
disp(outputCellArray);
{2×2 double} {2×2 double} {2×2 double} {2×2 double}
% Print the values of each 2x2 array
for i = 1:numel(outputCellArray)
fprintf('Cell %d:\n', i);
disp(outputCellArray{i});
end
Cell 1:
1 3 2 4
Cell 2:
1 3 2 4
Cell 3:
1 3 2 4
Cell 4:
1 3 2 4
---------------------------------------------------------------------------------------------------------------------------------------------------------
If you find the solution helpful and it resolves your issue, it would be greatly appreciated if you could accept the answer. Also, leaving an upvote and a comment are also wonderful ways to provide feedback.
Professional Interests
  • Technical Services and Consulting
  • Embedded Systems | Firmware Developement | Simulations
  • Electrical and Electronics Engineering
Feel free to contact me.
  1 件のコメント
Dyuman Joshi
Dyuman Joshi 2024 年 1 月 15 日
The output from your code is not correct (compared to the expected output).

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

カテゴリ

Help Center および File ExchangeArray Geometries and Analysis についてさらに検索

タグ

製品


リリース

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by