MATLAB: How to create a function which accepts a name of a mat-file and returns a structure array with fields’ Name and Size

.mat filenamesize;structure array

I don't know if I'm on the right way to solvning this. Here is the assignment:
" Create a function which accepts a name of a mat-file and returns a structure array with fields’ Name and Size. The number of elements in the structure array corresponds to the number of the variables in the mat-file. Name nameand Size fields contain information about name and size of variables. Prepare several mat-files to demonstrate the function’s performance. Tips: Use the built-in function size to obtain a variable’s size."
Here is my function:
function se=se(name)
filename = name;
filename = name;
myVars = {'x','y','caption'};
S = load(filename,myVars{:})
end
And here are my two vector saved as "ma":
x=magic(20)
y=magic(10)

Best Answer

  • Lets go through your proposed code:
    function se=se(name)%don't give your ouput the same name to your output as your function
    filename = name;%no need to rename the variable, you can also just use this name in the function def
    filename = name;%no need to repeat this statement
    myVars = {'x','y','caption'};%you don't need to define yourself what variables to load
    S = load(filename,myVars{:})%you're on the right track by loading into a struct
    end
    You can skip those first three lines. Then you have a struct with the contents of the mat file. So your next step is to find the name and size of each variable, which is now the name and size of each field in your struct.
    You can use the fieldnames function and make use of the fact that you can do something like this:
    a=struct;a.foo='bar';
    field_name='foo';
    disp( a.(field_name) )%prints 'bar' to the command window