Filter löschen
Filter löschen

Covert a cell to multidimensional matrix

1 Ansicht (letzte 30 Tage)
Orion
Orion am 12 Mär. 2016
Kommentiert: Orion am 14 Mär. 2016
I have a 50 X 1 cell array, A, and each cell contains an m x 100 matrix, where m is variable and not the same for each of the cells. I would like to convert this cell array to a 3D matrix, Anew(M,100,50), where M is the first dimension of the matrix with biggest rows, and pad zero for the small matrices. I tried cell2mat but it concatenated the cell into a 2D matrix ([...],100). I also tried:
for ii=1:50
Anew(:,:,ii)=A{ii};
end
but I got
Subscripted assignment dimension mismatch.
error. Does anyone know how it can be done?
Thanks
This is the first 6 cells of A:
A =
[ 44x100 double]
[ 80x100 double]
[103x100 double]
[ 96x100 double]
[ 94x100 double]
[ 92x100 double]
.
.
.

Akzeptierte Antwort

Azzi Abdelmalek
Azzi Abdelmalek am 12 Mär. 2016
%------------Example---------------------------
s=arrayfun(@(x) randi(5,randi(5),100),1:5,'un',0)
%---------------the code-------------------------
n=max(cellfun(@(x) size(x,1),s))
m=size(s{1},2)
a=cellfun(@(x) [zeros(n-size(x,1),m);x],s,'un',0)
out=cat(3,a)
  3 Kommentare
Guillaume
Guillaume am 14 Mär. 2016
Azzi made a mistake in the last line, it should be
out = cat(3, a{:});
Please use good variable names in your code, not m, n, a, etc. It makes the code so much easier to maintain:
%input cell array: c
maxheight = max(cellfun(@(m) size(m, 1), c);
resizedmatrices = cellfun(@(m) [m; zeros(maxheight - size(m, 1), size(m, 2)], c, 'UniformOutput', false);
out = cat(3, resizedmatrices{:});
Orion
Orion am 14 Mär. 2016
thanks

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Image Analyst
Image Analyst am 12 Mär. 2016
Try this (untested) intuitive looping method:
Anew = zeros(m, 100, 50); % Initialize
for thisCellIndex = 1 : 50
% Extract contents of this particular cell.
% It will be a 1 x 100 row vector.
thismx100Array = A{thisCellIndex};
finalZ = min([size(Anew, 3), length(thismx100Array )]);
% Put this row vector into a column vector along the "Z" dimension.
for z = 1 : finalZ
Anew(1:m, 1:100, ii) = thismx100Array(z);
end
end
It's hard to do much more without your actual data.
  1 Kommentar
Orion
Orion am 14 Mär. 2016
m is changing in each cell. but I think to use your suggestion, it should be the biggest first index of the matrices.

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Cell Arrays finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by