简体   繁体   English

加载和保存文件名是字符串的特定对象

[英]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? ...最好的方法是什么?

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 ). 尚不清楚您的问题是什么,但是如果您知道要保存的变量名,则可以将变量名与文件路径(由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. 我会说这并没有真正降低代码的可读性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM