How to load multiple specified variables in a specified mat file?

48 次查看(过去 30 天)
For example, I want load Train_data Train_label Test_data Test_label in each all_number.mat, such as in figure.
But there have bugs in 'file'. How to debug?
for iter_all = 1:20
file = ['all',num2str(iter_all),'.mat'];
load('file' Train_data Test_data Train_label Test_label)
end
ask.jpg

回答(1 个)

Stephen23
Stephen23 2020-1-7
编辑:Stephen23 2020-1-7
Your code does not make much sense: you added single quotes around the variable name (making it a literal string), you removed the single quotes from the fieldnames (making them attempts to access variables or call functions), and you did not use any commas to separate the input arguments. You should read the load documentation and look at its examples.
Something like this should get you started (the data will be in cell array C:
N = 20;
C = cell(1,N); % preallocate
T = {'Train_data','Test_data','Train_label','Test_label'};
for k = 1:N
F = sprintf('all%d.mat',k);
C{k} = load(F,T{:});
end
I recommend concatenating the scalar structures into one non-scalar structure:
S = [C{:}]; % concatenate all loaded data into one structure
which you can access using indexing, e.g. the first file:
S(1).Train_data
S(1).Test_data
  4 个评论
z cy
z cy 2020-1-7
OK,thank you again. Your inspiration have solved my question.
But I dont need to load all data at once. hhha, I am not clearly express
Stephen23
Stephen23 2020-1-7
"But I dont need to load all data at once."
I don't see the relevance. Loading into an output structure will make your code more robust.
Consider what your code would do if one of the files does not contain one of those variables, or if it contains a variable with the same name as one that you use in your code... you would get some very unpredictable behaviors.... simple to avoid by just loading into an output variable.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Workspace Variables and MAT-Files 的更多信息

标签

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by