필터 지우기
필터 지우기

How to load numbers from a text file to a .mat file?

조회 수: 20 (최근 30일)
Sweet Nemesis
Sweet Nemesis 2022년 1월 6일
댓글: Voss 2022년 1월 6일
I have a text file in the following format. How can I load it to a .mat file in its present form?
5
3
3 2 3 4
2 -1 5
3 1 -3 -4
  댓글 수: 4
Walter Roberson
Walter Roberson 2022년 1월 6일
The only way to get it "exactly like it comes from the file" is in text form.
MATLAB does not have any way to represent arrays that have varying numbers of columns per row (or varying number of rows per column.) There is no way, in MATLAB, to represent "holes" -- you cannot, for example, have a matrix
3 2 3 4
2 -1 5 <hole>
3 1 -3 -4
The closest you can get would be to put NaN in the empty locations.
Sweet Nemesis
Sweet Nemesis 2022년 1월 6일
I am ok with filling the missing values with zero or NaN to make a square matrix. How is that accomplished?

댓글을 달려면 로그인하십시오.

채택된 답변

Walter Roberson
Walter Roberson 2022년 1월 6일
filename = 'https://www.mathworks.com/matlabcentral/answers/uploaded_files/855395/text.txt';
data = readmatrix(filename)
data = 3×4
3 2 3 4 2 -1 5 NaN 3 1 -3 -4
  댓글 수: 2
Sweet Nemesis
Sweet Nemesis 2022년 1월 6일
Thank you! Is there a way to get the first two lines included in the matrix?
Walter Roberson
Walter Roberson 2022년 1월 6일
filename = 'https://www.mathworks.com/matlabcentral/answers/uploaded_files/855395/text.txt';
opts = detectImportOptions(filename);
opts.DataLines = [1 inf];
data = readmatrix(filename, opts)
data = 5×4
5 NaN NaN NaN 3 NaN NaN NaN 3 2 3 4 2 -1 5 NaN 3 1 -3 -4

댓글을 달려면 로그인하십시오.

추가 답변 (2개)

Mathieu NOE
Mathieu NOE 2022년 1월 6일
hi
maybe this
(I assumed you want each individual value stored in a cell)
the cell array can be of course saved to a mat file
a = readcell('data.txt',"Delimiter"," ")
a = 5×4 cell array
{[5]} {1×1 missing} {1×1 missing} {1×1 missing}
{[3]} {1×1 missing} {1×1 missing} {1×1 missing}
{[3]} {[ 2]} {[ 3]} {[ 4]}
{[2]} {[ -1]} {[ 5]} {1×1 missing}
{[3]} {[ 1]} {[ -3]} {[ -4]}
save test.mat a
  댓글 수: 1
Sweet Nemesis
Sweet Nemesis 2022년 1월 6일
Will this load like a matrix for operations? I am gettting a 1X4 cell with metadata.

댓글을 달려면 로그인하십시오.


Voss
Voss 2022년 1월 6일
You can read the file into a character array called text and save it to a .mat file:
% read characters from text file:
fid = fopen('text.txt');
text = fread(fid,'*char').';
fclose(fid);
% save to mat:
save('text.mat','text');
Then load the .mat file to check that it is the same as the text file:
S = load('text.mat');
disp(S.text);
5 3 3 2 3 4 2 -1 5 3 1 -3 -4
  댓글 수: 2
Sweet Nemesis
Sweet Nemesis 2022년 1월 6일
Will this load like a matrix? I need integers for the algorithm I'm using.
Voss
Voss 2022년 1월 6일
No, this will load like text.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Text Files에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by