Create a matrix that has a vector in each cell
조회 수: 19 (최근 30일)
이전 댓글 표시
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.
댓글 수: 7
답변 (1개)
Walter Roberson
2021년 12월 27일
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
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:
- Open a file for writing
- write out the number of rows and number of columns on the first output line
- 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.
- 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
- writematrix() number of rows and number of columns and length of vector to a file (creating the file)
- reshape() the matrix to 2D, like AR = reshape(A, [], size(A,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.
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Large Files and Big Data에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!