# Create a matrix that has a vector in each cell

2 views (last 30 days)
Emilio Pulli on 27 Dec 2021
Answered: Walter Roberson on 27 Dec 2021
I need to create a matrix that has a vector in each cell and I need to save it as a .dat file in order to be opened by another MATLB script and easily be used into concatenated for cycles. Therefore I need a matrix that can be easily indexed.
Walter Roberson on 27 Dec 2021
importdata() cannot handle 3D matrices.

Walter Roberson on 27 Dec 2021
I need to create a matrix that has a vector in each cell
Example:
M = 3; N = 4; L = 5;
A = cell(M, N);
V = zeros(1,L);
for n = 1 : N
for m = 1 : M
V = V + randn(1,L); %in other words, it can be something computed
A{m, n} = V;
end
end
A
A = 3×4 cell array
{[ -0.5335 0.7021 1.8754 -0.9391 -0.2890]} {[ 1.2258 0.2606 -1.5830 -1.7081 -2.3477]} {[2.3842 -1.0368 0.5194 -0.1599 -2.7099]} {[ 1.8332 -5.4159 -1.0653 3.1037 0.3140]} {[ 1.0806 0.0145 -0.3853 -1.5901 -1.5626]} {[0.8038 -0.6080 -1.5164 -0.9334 -2.4951]} {[1.7125 -2.2481 -1.0013 1.4118 -2.1413]} {[2.8896 -7.8279 -2.8225 2.8576 -0.7019]} {[1.4175 -0.8808 -1.2932 -2.1136 -2.5441]} {[ 1.9479 0.5358 -1.0151 -0.8865 -3.0931]} {[ 2.2016 -4.2659 -0.5048 1.7922 0.0979]} {[3.8184 -7.4239 -2.4685 1.4305 -0.7520]}
This is a 2D matrix with a vector in each cell.
A simple .dat file that can be imported by MATLAB with the function importdata, containing only numbers
That is a problem. You do not have a numeric matrix, you have a Cell Array.
As outsiders, we have to presume that the vectors can be of different length for each location -- if they were all the same location you would have used a 3D array instead of a matrix with a vector at each cell.
It is possible to write something like that out to a text file, but it would take a little bit of work to load it. Something like:
1. Open a file for writing
2. write out the number of rows and number of columns on the first output line
3. proceed through the cell array in linear order, all of the first row, all of the second row, and so on. For each cell, write out the elements of the vector on a line by themselves. This obeys the rule of "containing only numbers" while allowing different cells to be different length; the length of each cell entry is implied by the number of entries on the line.
4. close the file
If you are happen to be able to use a 3D numeric matrix instead of a matrix with a vector at each cell, if the vector can be along the third dimension because they are all equal size, then I would suggest
1. writematrix() number of rows and number of columns and length of vector to a file (creating the file)
2. reshape() the matrix to 2D, like AR = reshape(A, [], size(A,3))
3. writematrix() the reshaped matrix, using append mode
To restore: readmatrix() just the first line to get the original dimension. Then readmatrix() the 2nd line onward. reshape() the result to the dimensions read from the first line.