I have a tensor stored in a file (each line of file is a matrix). In Matlab, I would like to read each line and then create a tensor of size number of lines * size(matrix at each line) I am just wondering how to create a tensor from n matrix of same size?
1 Answer
You can use cat instruction, for creating a tensor.
See http://www.mathworks.com/help/matlab/ref/cat.html
Example:
Suppose you have 3 matrices: R, G, and B, size 100x100 each.
Use: RGB = cat(3, R, G, B);
Now RGB is 100x100x3 tensor.
You can also use the following example:
%Initialize tensor with dimensions 3x4x5
T = zeros(3, 4, 5);
%Fill T with random 3x4 "plain" matrices:
for i = size(T, 5);
A = rand(3, 4);
T(:, :, i) = A;
end
Reading lines, converting to matrices using reshape, and place matrices in a tensor:
Suppose you have a text file were each line is a matrix.
Suppose you know matrix size, and number of matrices, and you want to create a tensor.
I created the following example file called rows.txt.
1 1 1 1 1 1 1 1 1 1 1 1
2 2 2 2 2 2 2 2 2 2 2 2
3 3 3 3 3 3 3 3 3 3 3 3
4 4 4 4 4 4 4 4 4 4 4 4
5 5 5 5 5 5 5 5 5 5 5 5
The following code, initialize a 3x4x5 tensor, read a line, convert it to matrix, and insert to the tensor:
%Initialize tensor with dimensions 3x4x5
T = zeros(3, 4, 5);
f = fopen('rows.txt', 'r');
for i = 1:5
R = fscanf(f, '%f\n', [1, 3*4]); %Read row from file into row vector R.
A = reshape(R, [3, 4]); %Reshape R to 3x4 matrix.
T(:, :, i) = A;
end
fclose(f);
Result:
T(:,:,1) =
1 1 1 1
1 1 1 1
1 1 1 1
T(:,:,2) =
2 2 2 2
2 2 2 2
2 2 2 2
T(:,:,3) =
3 3 3 3
3 3 3 3
3 3 3 3
T(:,:,4) =
4 4 4 4
4 4 4 4
4 4 4 4
T(:,:,5) =
5 5 5 5
5 5 5 5
5 5 5 5
Another alternative:
Read entire text file into a vector, and use reshape to convert it to a tensor:
f = fopen('rows.txt', 'r');
%Read entire file into vector A.
A = fscanf(f, '%f');
%Reshape vector A into 3x4x5 tensor.
T = reshape(A, [3, 4, 5]);
fclose(f);
4 Comments
T = permute(T, [2, 1, 3]);