필터 지우기
필터 지우기

read txt file contains multiple arrays with different sizes

조회 수: 11 (최근 30일)
Amal Saad
Amal Saad 2017년 3월 28일
답변: Prateekshya 2024년 7월 23일
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
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
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.

카테고리

Help CenterFile Exchange에서 Just for fun에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by