How to read a matrix line by line in a for loop from a txt file and save it as a 4-dimensional matrix?
6 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Rafaela Rizzo
am 26 Mär. 2020
Bearbeitet: Rafaela Rizzo
am 26 Mär. 2020
I have a txt file, 'matrix.txt', which has 2 matrices of 1400 rows and 1 column each (they are separeted by a space). To save the file into a matrix, I did the following:
matrix = readmatrix('matrix.txt');
which is 1400x2.
But, I have to read each line and each column in a for loop to store the values into another matrix of dimension 4. The loop is described below:
for i = 1:10
for j = 1:10
for k = 1:7
for a = 1:2
big_matrix1(i, j, k, a) = matrix( ?, 1)
big_matrix2(i, j, k, a) = matrix( ?, 2)
end
end
end
end
Then, my question is where I put the question mark. The loop must work in a sequential way, reading each line of matrix( , 1) at a time. E.g.,
big_matrix1(1,1,1,1) = matrix(1,1)
big_matrix1(1,1,1,2) = matrix(2,1)
big_matrix1(1,1,2,1) = matrix(3,1)
big_matrix1(1,1,2,2) = matrix(4,1)
big_matrix1(1,1,3,1) = matrix(5,1)
big_matrix1(1,1,3,2) = matrix(6,1)
etc...
And that is why my matrix() has 1400 rows, because each row (of each column) is the output of each combination of i, j, k and a (10*10*7*2 = 1400).
So, I don't know how to read each line of matrix( , 1) and matrix( , 2) in a sequential way inside my loop. I cannot add another loop for matrix(n,1), where n=1:1400, because it would get me wrong results.
Also, I tried to use fgetl when reading my matrix.txt, by it stores it as a character vector, and I could not figure out how to read 1 column at a time in fgetl.
Thanks in advance for any help!
0 Kommentare
Akzeptierte Antwort
Adam Danz
am 26 Mär. 2020
Bearbeitet: Adam Danz
am 26 Mär. 2020
No need to use loops!
big_matrix1 = permute(reshape(matrix(:,1), [2 7 10 10]), [4,3,2,1]);
big_matrix2 = permute(reshape(matrix(:,2), [2 7 10 10]), [4,3,2,1]);
To confirm that the results are the same as your loop method,
c = 0; % row counter
big_mat1 = nan(10, 10, 7, 2); % pre allocation
big_mat2 = big_mat1; % pre allocation
for i = 1:10
for j = 1:10
for k = 1:7
for a = 1:2
c = c+1; % next row (this is a quick hack, for demo purposes)
big_mat1(i, j, k, a) = matrix( c, 1);
big_mat2(i, j, k, a) = matrix( c, 2);
end
end
end
end
% Test that the arrays match
isequal(big_matrix1, big_mat1) % True
isequal(big_matrix2, big_mat2) % True
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements 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!