Reputation: 5579
I have to load some data in a structure.
I do it inside a function.
assuming that my structure is called
loaddata
and the data are in
loaddata.corrected_data
how can I access to it within a function?
function loaddata_struct(path,namestruct)
loaddata = load(path);
data = loaddata.corrected_data; % this should change depending on the argument of the function (namestruct in this case)
end
how can I pass the name of the structure? in this case corrected_data...
Upvotes: 0
Views: 1594
Reputation: 381
The following code will return the structure's field with the name passed to loaddata_struct function:
function data = loaddata_struct(path,namestruct)
loaddata = load(path);
data = loaddata.(namestruct);
end
Upvotes: 1
Reputation: 35525
Do it as text and use isfield
and eval
. Isfield
will check if the string is a field of the struct, and if it is, then use eval to evaluate loaddata.fieldname
. Using isfield you make sure you never get an error, and you can do things in the else, like finding the data that has the most similar name to the one inserted, for example.
function loaddata_struct(path,fieldname)
loaddata = load(path);
if isfield(loaddata ,fieldname)
data = eval(strcat('loaddata.',fieldname));
else
error('Heeey mate, thats not a field')
end
end
Upvotes: -1
Reputation: 74940
You can use dynamic field names like so:
fieldOfInterest = 'corrected_data';
data = loaddata.(fieldOfInterest);
If you're loading from file, you can also access the data directly
data = load('theDataFile.mat','-mat',fieldOfInterest)
Upvotes: 2
Reputation: 221684
Use getfield
and if you need to work on a 1 x N
sized struct array -
function loaddata_struct(path,fname)
loaddata = load(path);
for k1 = 1:numel(loaddata)
data{k1} = getfield(loaddata(k1),fname);
end
return;
Thus, you can use it like this - loaddata_struct(path,'corrected_data')
Upvotes: 1