How to include text in m file as code?
9 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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 comentarios
Respuestas (1)
Walter Roberson
el 5 de Sept. de 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 comentario
Stephen23
el 5 de Sept. de 2024
"...the illusion of self-documenting the file name is worth it."
Calling a file-importing function with the filename also documents this information.
Ver también
Categorías
Más información sobre Large Files and Big Data en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!