P i
P i

Reputation: 30684

Load and save specific objects where filename is a string

I have:

save X a b c
:
load X a b

I would like:

TEMP_FOLDER = 'tmp'
save TEMP_FOLDER/X a b c         % syntax fail
:
load TEMP_FOLDER/X a b

Looks like I need the function version of load/save.

But I can't figure out from reading the help how to extract just the variables I need.

The best I can see is:

stuff = {'a', 'b'};
S = load( [TEMP_FOLDER 'X'], stuff{:} );
a = S['a'];
b = S['b'];
clear stuff S

really? Yuck!

Maybe I could do:

load( [TEMP_FOLDER 'X'] );

But then I lose information about which variables have been loaded, which makes the code harder to follow for someone else.

It looks as though the price of tidying up the file structure is code readability.

But can I have my cake and eat it?

Maybe I could:

cd( TEMP_FOLDER );
load X a b
cd( '..' );

... What's the best way to do this?

Upvotes: 0

Views: 23

Answers (1)

Suever
Suever

Reputation: 65430

It's a little unclear what your issue is, but if you know the variable names that you want to save, you can pass those to save along with the file path (constructed with fullfile).

save(fullfile(TEMP_FOLDER, 'X.mat'), 'a', 'b', 'c')

And for loading, you can do the same and explicitly pass the variables you want to load. This also has the added benefit of throwing an error if that variable isn't in the file.

% Load ONLY the variables: a, b
load(fullfile(TEMP_FOLDER, 'X.mat'), 'a', 'b');

As you've pointed out, if you want to store the variable names in a cell array you can easily do that with:

to_save = {'a', 'b', 'c'};
to_load = {'a', 'b'};

save(fullfile(TEMP_FOLDER, 'X.mat'), to_save{:})

load(fullfile(TEMP_FOLDER, 'X.mat'), to_load{:})

I would say that doesn't really decrease code readability.

Upvotes: 1

Related Questions