How to include text in m file as code?
9 ビュー (過去 30 日間)
古いコメントを表示
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.
0 件のコメント
回答 (1 件)
Walter Roberson
2024 年 9 月 5 日
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 件のコメント
Stephen23
2024 年 9 月 5 日
"...the illusion of self-documenting the file name is worth it."
Calling a file-importing function with the filename also documents this information.
参考
カテゴリ
Help Center および File Exchange で Large Files and Big Data についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!