How to include text in m file as code?

9 views (last 30 days)
태현 노
태현 노 on 5 Sep 2024
Commented: Stephen23 on 5 Sep 2024
I want to use kind of #include in C language.
What I want to do is to make one txt file filled with simple matrix of double data.
data.txt
1 10.2
2 20.3
3 30.4
...
And inside the code, I want to use wrap it in double matrix. (data.txt is located in same directory)
code.m
% blah blah
myMatrix = [data.txt]
% blah blah
Would this be possible?
I know there should be many alternative methods such as using data importers.
However, I'm just curious if I can do this.

Answers (1)

Walter Roberson
Walter Roberson on 5 Sep 2024
Yes, it is possible.
What you need to do is create a function file named data.m that looks something like
function datastruct = data()
datastruct.txt = readmatrix('data.txt');
end
Then when your code encounters
myMatrix = [data.txt]
it will execute the function data with no parameters. Function data will read in the file, and assign it into a struct with field named txt . Then the .txt part of [data.txt] will dereference the txt field, resulting in the data matrix.
Note that this will only work for files whose names happen to be the same as valid MATLAB identifiers. It could not be used for something like 'data - april.txt' or '123data.txt'
It seems a bit awkward to do this, but perhaps the illusion of self-documenting the file name is worth it.
  1 Comment
Stephen23
Stephen23 on 5 Sep 2024
"...the illusion of self-documenting the file name is worth it."
Calling a file-importing function with the filename also documents this information.

Sign in to comment.

Categories

Find more on Large Files and Big Data in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!