필터 지우기
필터 지우기

Reshape array of cells with different column sizes into matrix

조회 수: 4 (최근 30일)
Ardo Laaneots
Ardo Laaneots 2017년 12월 7일
답변: Jos (10584) 2017년 12월 7일
Hi. I need to reshape a T1 = [1x5] cell array, where each cell is a [5x1] cell array of numbers into a S1 = [m-by-n] matrix of numbers. The problem is the initial cell array T1 may have different number of rows in each cell - meaning I don't have a square shaped array to use " cell2mat " function.
Example:
T1=[1x5] cell array
T1{1} T1{2} T1{3} T1{4} T1{5}
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24
I need to add all of the columns together:
T2=
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24
And then reshape the array into [m-by-n] array (always square shaped), in this example S1=[3x8]:
S1=
1 2 3 4 5 6 7 8
9 10 11 12 13 14 15 16
17 18 19 20 21 22 23 24
I thought that maybe I could reshape T1 into [x-by-1] array and then reshape that array in to S1=[m-by-n]. But what should i do in order to get results like this:
T3=
1
2
3
4
...
24
And not like
1
6
11
16
21
2
...
24
Any help would be appreciated.
  댓글 수: 1
Stephen23
Stephen23 2017년 12월 7일
@Ardo Laaneots: is the shorter vector always the last one in the cell array?

댓글을 달려면 로그인하십시오.

채택된 답변

Jos (10584)
Jos (10584) 2017년 12월 7일
Here is a way:
T = {[1:5:21]',[2:5:22]',[3:5:23]',[4:5:24]',[5:5:20]'}
m=3
n=8
[M, tf] = padcat(T{:})
M = M.'
out = reshape(M(tf.'),n,m).' % swap m and n, and then transpose
PADCAT concatenates unequal sized vectors by padding shorter ones with NaNs. This function can be downloaded from the File Exchange: https://uk.mathworks.com/matlabcentral/fileexchange/22909-padcat-varargin-

추가 답변 (1개)

KL
KL 2017년 12월 7일
One approach is to make all elements equal in size by padding 0s or nans and then use cell2mat,
m = max(cellfun(@numel,T1));
for k = 1:numel(T1)
n = numel(T1{k});
if n<m
T1{k} = [T1{k}; nan(m-n,1)];
end
end
T2 = cell2mat(T1)'

카테고리

Help CenterFile Exchange에서 Cell Arrays에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by