Create a cell of array of cell filled with a matrix

3 Ansichten (letzte 30 Tage)
Mahdi Zarghami
Mahdi Zarghami am 19 Nov. 2016
Kommentiert: Tong Zhao am 27 Jun. 2022
I want to create an array which contains 14 cell A{1,1:14}. Each element should be filled with a cell so we reach to the point of having A{1,1:14}{1,1}. Then that element should be filled with a zero matrix of 4*4. Can everyone help me how to initial this matrix with zero value. Thanks,

Antworten (3)

Miguel Zerecero
Miguel Zerecero am 7 Feb. 2020
A = cell(1,14);
A(:,:) = {zeros(4,4)};
Cheers
  3 Kommentare
Image Analyst
Image Analyst am 27 Jun. 2022
@Tong Zhao yes, but like I said, that is probably not best. Cell arrays are meant for when the contents of the cells will not all have the same size or be of the same type (string, double, etc.). In the case where each cell has a 4x4 matrix in it, it is far better to just use a 3-D double array.
A = zeros(4, 4, 14);
Cell arrays are very slow and inefficient taking up much, much more memory than a numerical array.
See the FAQ on cell arrays:
Tong Zhao
Tong Zhao am 27 Jun. 2022
@Image Analyst Thank you for the reply. Indeed, I have an algorithm where I need to store data of different sizes. E.g.,
sampleData = {[1 2],[1 3; 6 2], [2 5; 7 9; 8 3], [4 5; 1 7]}
sampleData = 1×4 cell array
{[1 2]} {2×2 double} {3×2 double} {2×2 double}
And the size cannot be pre-determined, as it is essentially a tree-based search algorithm, you never know how many tree branches you need to fill up the space. I'd be happy to eliminate any cell array use if I can. But I guess in this case, there is no workaround.

Melden Sie sich an, um zu kommentieren.


KSSV
KSSV am 19 Nov. 2016
A=cell(1,14);
for i =1:14
A{i}=zeros(4);
end

Image Analyst
Image Analyst am 19 Nov. 2016
I don't think you've read the FAQ yet, so read that: http://matlab.wikia.com/wiki/FAQ#What_is_a_cell_array.3F. I don't think you want a cell array where each cell contains a cell that contains a 4 by 4 array. In fact I don't even know why you want a cell array AT ALL. There's just no reason for it. A regular 3-D double array would be much better. If you did, for some strange reason, want to be more complicated and use a cell array, you'd just have the cells contain the 4x4 array of doubles and not contain another cell. So you'd do
% Not recommended, but if you insist:
ca = cell(1, 14)
for col = 1 : length(ca)
ca{col} = zeros(4,4);
end
celldisp(ca)
Again, use a regular array instead:
A = zeros(4, 4, 14);

Kategorien

Mehr zu Matrix Indexing 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