user129412
user129412

Reputation: 775

Loading files with names containing multiple variables (MATLAB)

I'm trying to load about 40 files into MATLAB, all of who's names and locations are the same apart from 2 variable pieces. They each contain 5000 datapoints, which I want to combine into 1 single vector. They are HDF5 files, so I also have to specify the path inside the file, the name of which contains these variables too.

An example of loading one of these files would be

ROdata = double(h5read('directories\010340text2\010340text2.hdf5','/othertext2'));

Here, the variables would be 010340 and 2. So the general form is something like (n terms of x and y)

ROdata = double(h5read('directories\xtexty\xtexty.hdf5','/othertexty'));

Both x and y I have in an array already loaded into MATLAB.

From this point, I'm pretty clueless. I suppose num2str comes in somewhere, but I've tried a few things (like in the video http://blogs.mathworks.com/videos/2009/07/02/advanced-loading-files-using-their-names-for-variable-names/) but that doesn't work, as the variable part is inside the text, not at the end.

I could of course do so manually, but these 40 are from a series of around 300, so that'll be a lot of writing.

Upvotes: 2

Views: 515

Answers (2)

Lisa
Lisa

Reputation: 3526

How about something like this:

ROdata = double(h5read( ... 
  sprintf( 'directories/%06dtext%d/%06dtext%d.hdf5', 010340, 2, 010340, 2 ), ...
  sprintf( '/othertext%d', 2 ) ));

%# or more general:
x = 010340;
y = 2;
ROdata = double(h5read( ...
  sprintf( 'directories/%06dtext%d/%06dtext%d.hdf5', x, y, x, y ), ...
  sprintf( '/othertext%d', y ) ));

%# or even more general:
%# assume X is your array containing elements x, Y for y elements

ROdata = cell{ numel(X), 1 };
for ii=1:numel(X)
  ROdata{ii} = double(h5read( ...
    sprintf( 'directories/%06dtext%d/%06dtext%d.hdf5', X(ii), Y(ii), X(ii), Y(ii) ), ...
    sprintf( '/othertext%d', Y(ii) ) ));
end

Have a look at the sprintf function, it's quite neat.

In order for this to work, you need to use forward slashes, as backslahes act as escape characters. Another possibility would be to use '\\', but '/' is more readable and works as well.

Since the numbers in X may contain leading zeros: %06d adds zero padding such that the inserted number will always be 6 digits long.

Upvotes: 3

Cape Code
Cape Code

Reputation: 3574

What about using string concatenation?

ROdata = double(h5read(['directories\xtexty\' num2str(x) 'xtexty.hdf5'],['/othertexty' num2str(y)]));

Upvotes: 1

Related Questions