MATLAB: Load structure array with a function and extract the variables

function to extract variables from structure array

Hi,
I am trying to write a function that will load a generic file that is a structure array. Then I want to extract the variables (and perform some operations on them).
The problem is that i cannot extract them, because, I need to call the function with 'filename.mat', but when I then want to extract the variables, it does of course not work, because the name of the variable contains .mat, instead of only 'filename' – which i could use as the structure.
The array does have a variable called 'name', its value being the file name w/o the .mat extension.
My idea was to extract this value and turn it into a variable, but I cannot access it:
- with load(filename,'name') i get 'filename.mat' - and not 'filename'...
- and with filename = load(filename,'name') i get an empty structure array??
I hope I expressed myself clearly enough and that somebody can tell me what is wrong??
see the example:
- function [cube] = img(filename)
- load(filename)
- filename=load(filename, 'name')
- cube = filename.data;
- end
The warnings and error i get are:
_________________________________________________________________
Warning: Error occurred while trying to call loadobj on a dataset object: Reference to non-existent field 'props'. > In img at 7 Warning: Class 'dataset' is an unknown object class or does not have a valid 'loadobj' method. Object 'Norway_spruce_not_extracted_RA_ray' of this class has been converted to a structure. > In img at 7 Warning: Variable 'name' not found. > In img at 9 Reference to non-existent field 'data'.
Error in img (line 11) cube = filename.data;
___________________________________________________________
I really do not understand what is going on…??
Thank you in advance! Sophie

Best Answer

I did not understand exactly what you're trying to do. It sounds like you are trying to name your variables depending on the file that you load, which is never a good idea.
However, I can certainly explain the error message. The mat file that you are trying to load a file that contains a variable of type dataset. The version of matlab that you are using does not know what a dataset is. It's because either you're missing the required toolbox (e.g. there's a dataset type in the statistics and machine learning toolbox) or because it's a custom type for which you're missing the m file (in which case you need to ask whoever saved that mat file for the required m files).
In any case, without the required toolbox or necessary m file, you will not be able to load that mat file properly. You may be able to load part of the file using matfile but you'll always be missing the dataset.