MATLAB Answers

How do you load m-files that contain filenames with integers and strings?

1 view (last 30 days)
Brittny Freeman
Brittny Freeman on 18 May 2021
Edited: Stephen Cobeldick on 18 May 2021
I have a foler that containes multiple files with the following naming convention:
TTsim1Variable, TTsim2Variable, TTsim3Variable, TTsim4Variable....TTsim50Variable. Each "TT" files has the same number of rows and coloumns. Currently I am using the follwing code to load the data into my workspace:
B1 = load(sprintf('TTsim1Variable.mat'));
B2 = load(sprintf('TTsim2Variable.mat'));
B3 = load(sprintf('TTsim3Variable.mat'));
This is becoming quite tedious, is there a way to use the %d notation in the file names to make this process more efficent? Perhaps something like:
B1 = load(sprintf('TTsim%dVariable.mat'));

Answers (2)

the cyclist
the cyclist on 18 May 2021
Use the %d notation, and a cell array for storing:
for ii = 1:50
B{ii} = load(sprintf('TTsim%dVariable.mat',ii));
end

Stephen Cobeldick
Stephen Cobeldick on 18 May 2021
Edited: Stephen Cobeldick on 18 May 2021
"...is there a way to use the %d notation in the file names to make this process more efficent?"
Of course, the documentation shows the basic concept:
For your files, something like this:
P = 'absolute or relative path to where the files are saved';
N = 50;
C = cell(1,N);
for k = 1:N
F = sprintf('TTsim%dVariable.mat',k);
C{k} = load(fullfile(P,F));
end
S = [C{:}]; % optional, if all files contain the same variables.

Community Treasure Hunt

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

Start Hunting!