Create loop to load .mat file and store values to a matrix.

2 views (last 30 days)
I have multiple .mat files with values for x and y. The variables in each file has the same name (x,y) , but different values.
I need to create a loop or a function that loads each file and will open them one at a time and save x and y (maybe in a matrix) in order to be able to plot them. Any thoughts?

Accepted Answer

Stephen23
Stephen23 on 7 Dec 2021
Edited: Stephen23 on 7 Dec 2021
This should get you started. In the absence of any data desription I assumed that withinin each file x and y are scalar. You will need to adapt to suit your filenames, data sizes, etc.:
P = 'absolute or relative file path to where the files are saved';
S = dir(fullfile(P,'*.mat'));
S = natsortfiles(S); % optional, if required download from FEX 47434.
for k = 1:numel(S)
F = fullfile(P,S(k).name);
S(k).data = load(F);
end
D = [S.data];
X = vertcat(D.x);
Y = vertcat(D.y);
plot(X,Y)

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!