0

I have a folder with a bunch of .mat files with many different variables each. I want to store (an) individual variable(s) into separate matrices. I made a for loop with which I loaded every file by name but that only gives me the last .mat file. I'm new to Matlab and I'm assuming there's a really simple way to go about this but I haven't had luck finding anything.

Thanks!

Edit: OK so I have a whole bunch of .mat files with a variable X in each one. I want to store all the Xs into separate matrices that correspond to each separate .mat file.

user2171003
  • 41
  • 1
  • 6
  • Your question is not very clear, try describing a minimal exemple of your problem in detail. If your problem is that your mat files contain variables that have the same name, and loading them result in variables being overwritten, then you should check this question: http://stackoverflow.com/q/9104326 (Shai's answer is similar). – Aabaz Mar 14 '13 at 18:14

2 Answers2

1

Load(filename) on its on own will load variables into the work space but, as you noticed, these get over written each time you load new variables with the same names. S = load(filename) will load the variables into a structure array. You can then access each variable by name and save it in an array. For example:

% create two files containing variables with the same names    
x = 1;
y = 2;
save("test1.mat")

x = 10;
y = 20;
save("test2.mat")

% load the saved files and store the variables x and y in vectors
for i  = 1:2
    temp = load(["test", num2str(i), ".mat"]);
    xVec(i) = temp.x;
    yVec(i) = temp.y;
end

In response to your edit, you can save all the variables from each file in a matrix like this:

% load the saved files and store the contents of each file in a matrix
dataArray = {};
for i  = 1:2
    temp = load(["test", num2str(i), ".mat"]);
    dataArray{i} = [temp.x, temp.y];
end

The cell array dataArray will contain a matrix for each file.

Molly
  • 13,240
  • 4
  • 44
  • 45
0

load the files into a variable

ld{ii} = load( filename{ii} );

Now ld{ii} is a struct with a field per variable in file filename{ii}

Shai
  • 111,146
  • 38
  • 238
  • 371