how to load variables from files when you know the file name?

1 visualización (últimos 30 días)
Alan Williams
Alan Williams el 26 de Feb. de 2016
Respondida: Shivam Chaturvedi el 2 de Mzo. de 2016
So I have 11 files in a folder named pv01.dat to pv11.dat. I have used the following to load the data into the workspace:
datafiles = dir('*.dat'); %%Finding all dat files
num = length(datafiles); %%counting how many
name = {datafiles.name}; %%Getting the name
[~, index] = sort(name); %%sorting the name
name = name(index); %% " " "
for i = 1:1:num %%loop loading data
load(name{i});
disp(name{i});
end;
So I have a string with the name of every data file called name. How can I then use these strings to extract data from the files. Ideally I would like to be able to carry out the equivalent of:
P{1} = pv01(:,1);
P{2} = pv02(:,1);
P{3} = pv03(:,1);
P{4} = pv04(:,1);
P{5} = pv05(:,1);
P{6} = pv06(:,1);
P{7} = pv07(:,1);
P{8} = pv08(:,1);
P{9} = pv09(:,1);
P{10} = pv10(:,1);
P{11} = pv11(:,1);
In the loading loop but in a very compact and reusable way. I cant seem to fathom how I can get the file name string into the load command. I can envision having to truncate the extension .dat and leave the strings as pv01...pv11 and then use something along the lines of:
p{i} = truncated_name{i}(:,1);
But for obvious reasons this is incorrect. Any help is much appreciated.

Respuestas (1)

Shivam Chaturvedi
Shivam Chaturvedi el 2 de Mzo. de 2016
Hi Alan,
You can use the load command's following syntax to load the variables from each of the file into a struct:
S = load(filename)
Then, the variables from the file filename would be loaded into the struct S. This works well for MAT-files. For more info and examples, refer to http://www.mathworks.com/help/matlab/ref/load.html
Also I think you probably have a variable by the same name in each of those files as well. So, if it's like there's a pv01 variable in the file pv01.dat, then after loading all the variables I would get the variable pv01 by a special syntax like the following:
S = load('pv01.dat');
p{1} = S.('pv01');
% You can obviously replace the string constants here by variable names which
% are strings and it would work the same way
Hope that helps!

Categorías

Más información sobre Characters and Strings en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by