MATLAB: Save and Load .mat files with different names that numerically go up automatically. Maybe in a for loop

automaticallydifferent namefile namefor looploadnamingsave name

How do I automatically name and save files at iteration of a for loop with the names of the files being attached to the file name to be saved? e.g. first run nameoffile_1, second run nameoffile_2 etc?
And then be able to load them later, also automatically for a set of the runs I've done in the for loop? E.g. if I wanted to load the files from runs 1-10, or 5-20?
At the moment, I'm saving the file as such:
for j=1:n
fvalagg=j^2 %as an example
save(['c://Outputs/Scenario' num2str(j) '_fvalagg.mat'],'fvalagg')
end
This seems to correctly save each fvalagg as "Scenario_1fvalagg", then "Scenario_2fvalagg" etc.
But then when I load them, the name of the file loaded is still "fvalagg", rather than "Scenario_1fvalagg".
That's not a problem, as long as there is a way to load multiple of these in one go, without them all overwriting each other as fvalagg.
As I will want to analyse the data for e.g. scenarios 1-10, so I would like to be able to load all the fvalagg generated from loop of j=1:10, and have them loaded up in separate files e.g. fvalagg1, fvalagg2 etc open at the same time.
Thanks!

Best Answer

"...as long as there is a way to load multiple of these in one go, without them all overwriting each other as fvalagg"
This is trivial using indexing into an array... and this is the recommended approach.
Simply load into an output argument (which is a scalar structure), obtain the data from whichever fields you want, and then use indexing to allocate that data to a cell array (or a structure, a table, a numeric array, etc.). For example:
D = 'c://Outputs';
V = 5:20;
N = numel(V);
C = cell(1,N); % preallocate
for k = 1:N
F = sprintf('Scenario%d_fvalagg.mat',V(k));
C{k} = load(fullfile(D,F)); % allocate using indexing
end
S = [C{:}] % optional
All of the files' data will be in the non-scalar structure S:
".I would like... have them loaded up in separate files e.g. fvalagg1, fvalagg2 etc"
Putting numbers into variable names is a sign that you are doing something wrong. Do NOT do this unless you want to force yoiurself into writing slow, complex, buggy code that is hard to debug: