Load constants from file

21 次查看(过去 30 天)
Macko
Macko 2011-7-1
Hi,
I'm looking for a way to load constants defined in an external file to the workspace, keeping their original names.
I generate a row of constants, using an external application, that looks like this:
A=1
B=2
C=3
Now, I'd like to load this data (which is stored in a file) into the Matlab workspace, preserving the constant names, so that, after the import, the A, B and C constants with the corresponding values are visible in the workspace and usable in my model.
I have full control on the imported file's format, too.
Any idea on how to achieve this, is greatly appreciated! Thank you!

采纳的回答

Gerd
Gerd 2011-7-1
Hi Cristian,
you can use the eval('') command to do what you described. First you have to open the file, read line by line and
eval('A=1');
Then you have the variable in your base workspace.
Gerd
  2 个评论
Macko
Macko 2011-7-1
Thanks a lot!
I don't want to impose but do you happen to have some sample code on that?
Macko
Macko 2011-7-1
Solved! :)
fid = fopen('var.m');
while 1
tline = fgetl(fid);
if ~ischar(tline)
break
end
eval(tline)
end
Thank you so much!

请先登录,再进行评论。

更多回答(2 个)

Daniel Shub
Daniel Shub 2011-7-1
Another solution is to create a file, lets call it loadconstants.m. In that file just put
A=1;
B=2;
C=3;
Then when you want to load the constants simply type
loadconstants
  1 个评论
Macko
Macko 2011-7-1
Thanks! That would indeed be another possibility.

请先登录,再进行评论。


ravindra
ravindra 2011-7-2
Hello, I am also having same problem means I have a file name A which is having 12X36 matrix. I want to use it in my model which I am writting in .m file. So how to use this file in my program. Please help me Thank you
  1 个评论
Macko
Macko 2011-7-4
Can you post your file content? That might enable us to answer your question more precisely. Thanks!

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Variables 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by