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

55 visualizzazioni (ultimi 30 giorni)
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

Risposte (1)

Stephen23
Stephen23 il 7 Gen 2020
Modificato: Stephen23 il 7 Gen 2020
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 Commenti
z cy
z cy il 7 Gen 2020
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 il 7 Gen 2020
"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.

Accedi per commentare.

Categorie

Scopri di più su Workspace Variables and MAT-Files in Help Center e File Exchange

Tag

Community Treasure Hunt

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

Start Hunting!

Translated by