1

I am trying to load a MAT file and getting a dataset as an output. If I run

a = load('foo.mat');

a is a structure and not a dataset. In order to get a dataset I need to run the following code

load('foo.mat');
a = foo;

Though, in this way in my workspace I have two identical datasets, specifically a and foo.

Is there a way to just write a line of code and import the MAT file and get a single dataset rather than two?

Dev-iL
  • 23,742
  • 7
  • 57
  • 99
federico
  • 65
  • 1
  • 6
  • In the secong option, If you dont assign `a=foo`, you have one dataset called `foo` – Adiel Jan 31 '19 at 12:05
  • Yes, do `load('foo.mat');` and you will only have `foo`. If you want it to be called `a`, then add `clear foo` in the end to your second snippet – Ander Biguri Jan 31 '19 at 12:05
  • @Adiel yes I forgot to add that I did not want the variable to be called 'foo' (in my actual case the name is very long and relatively unusable). – federico Jan 31 '19 at 13:42
  • Note that MATLAB doesn’t copy the data when you do `a=foo`. As long as you don’t modify one of these variables, you will have the data in memory only once. – Cris Luengo Jan 31 '19 at 14:01
  • You can use `a = load('foo.mat'); a = a.foo;`. It is chip and actually no copy is made. – rahnema1 Jan 31 '19 at 16:29

2 Answers2

5

It's a bad idea to do load w/o assigning it to a variable, because this makes it difficult to track changes to your workspace.

I would generally do,

a = struct2array(load('foo.mat'));

But this has some limitations (e.g. it only works if foo.mat contains a single variable).

Dev-iL
  • 23,742
  • 7
  • 57
  • 99
  • _it only works if `foo.mat` contains a single variable_ You can use `a = struct2array(load('foo.mat', 'foo'));` – Luis Mendo Jan 31 '19 at 14:31
  • @LuisMendo Yes, thanks for the clarification. I meant that the command _as it is written_ is good for a single variable. – Dev-iL Jan 31 '19 at 15:12
4

Create a separate function to load your data.

function[foo] = loader()
load('foo.mat');
end

Then call it as:

a = loader();

Because the function has a closed scope, you can load the variables with the names they have in the mat file. When the function returns, you assign the value to whatever name you want.

Mefitico
  • 816
  • 1
  • 12
  • 41
  • This is definitely better than loading directly into the active workspace, however the issue with a function like this is that `foo` is technically not being defined in the scope of the function, which issues a warning IIRC. I would suggest adding "invalid" default values (e.g. `NaN`) for all expected outputs, or testing with `exist` that all desired variables were actually created. – Dev-iL Jan 31 '19 at 15:24
  • @Dev-iL Adding `%#ok` will suppress the warning on the text editor. Depending on your coding standards, that might be good enough. (I do admit this is kinda of a YOLO suggestion on my part). – Mefitico Jan 31 '19 at 15:30