read txt file contains multiple arrays with different sizes
2 次查看(过去 30 天)
显示 更早的评论
hi I have a txt file contains a 1D matrix and 2- 2D matrices, they are separated by new line. morover, the 2D matrices elements are separated by space how I read these matrices and put them in three arrays or cells
1 个评论
Guillaume
2017-3-28
You need to provide more details (e.g. how do you find the end of the first 2D matrix) or even better attach a sample file.
回答(1 个)
Prateekshya
2024-7-23
Hello Amal,
To read a text file containing a 1D matrix and two 2D matrices separated by new lines and spaces, you can use MATLAB's file I/O functions. Let us consider this example file:
File name: data.txt
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
1 2 3
4 5 6
7 8 9
10 11 12
13 14 15
16 17 18
The below steps can be followed for reading the above file:
- Use "fopen" to open the file.
- Use "fgetl" to read lines from the file.
- Use "str2num" to convert string lines to numeric arrays.
- Store the 1D matrix in a vector.
- Store the 2D matrices in separate arrays or cell arrays.
Here is a MATLAB script to achieve this:
% Open the file
fileID = fopen('data.txt', 'r');
if fileID == -1
error('File could not be opened.');
end
% Initialize variables
matrix1D = [];
matrix2D_1 = [];
matrix2D_2 = [];
currentMatrix = 1;
tempMatrix = [];
% Read the file line by line
while ~feof(fileID)
line = fgetl(fileID);
% Check if the line is empty (new line)
if isempty(line)
% Store the temporary matrix into the appropriate variable
if currentMatrix == 1
matrix1D = tempMatrix;
elseif currentMatrix == 2
matrix2D_1 = tempMatrix;
elseif currentMatrix == 3
matrix2D_2 = tempMatrix;
end
% Reset the temporary matrix and increment the current matrix counter
tempMatrix = [];
currentMatrix = currentMatrix + 1;
else
% Convert the line to a numeric array
numericLine = str2num(line); %#ok<ST2NM>
% Append the numeric array to the temporary matrix
tempMatrix = [tempMatrix; numericLine];
end
end
% Store the last matrix (if any)
if currentMatrix == 1
matrix1D = tempMatrix;
elseif currentMatrix == 2
matrix2D_1 = tempMatrix;
elseif currentMatrix == 3
matrix2D_2 = tempMatrix;
end
% Close the file
fclose(fileID);
% Display the results
disp('1D Matrix:');
disp(matrix1D);
disp('2D Matrix 1:');
disp(matrix2D_1);
disp('2D Matrix 2:');
disp(matrix2D_2);
The code can be modified according to the requirement. I hope this helps!
Thank you.
0 个评论
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!