how to load variables from files when you know the file name?
5 次查看(过去 30 天)
显示 更早的评论
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.
0 个评论
回答(1 个)
Shivam Chaturvedi
2016-3-2
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!
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Characters and Strings 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!