Reputation: 43
In matlab
I have a function which should take in a file name.
This file has a struct in it, later this file should be executed with in the function so that the struct will be loaded to the work space.
For example:
My function is hello(a)
, where 'a' is a file name, this file has a struct.
On executing the file in command window this struct will be loaded in the workspace. Same way I want the struct to be loaded in to the workspace when I call the function.
I tried eval(a)
, but this is not loading the struct in the file to the workspace.
From the file name how will I obtain the struct name, even though I know that there is a struct in the file, but this is going to vary dynamically.
So how should I return the structure in function?
Upvotes: 1
Views: 2369
Reputation: 5073
Try eval
:
function mystruct = readstruct(filename)
% ... read in text from file here ...
eval(text)
For example, assume your file contains text 'mystruct.myval = 1'
, then after reading the file contents into string text
, eval(text)
returns
mystruct =
myval: 1
To load the structure into the workspace, the function should return the structure.
If the file contains arbitrary data (presumably but not necessarily in ascii format) then you can simply assign it to a structure after the file is read:
function mystruct = readstruct(filename)
% ... read in text from file here ...
% ... perform conversion of data type ...
mystruct.value = values
Upvotes: 0
Reputation: 1353
I am not sure whether you want the struct (or structs) inside the file to be copied automatically to the workspace, or if you want to assign the data yourself.
The following solution copies all variables from file a
to the "base"-workspace automatically using the assignin()
function. The solution also assumes that you give it a file for a .mat file.
function hello(a)
all_structs = load('-mat', a);
var_names = fieldnames(all_structs);
for k = 1:length(var_names)
assignin('base', var_names{k}, all_structs.(var_names{k}));
end
end
Upvotes: 1