Looping through list of files to access variable names

5 views (last 30 days)
Hi all, this might be very simple but i've been struggling to get solution for this all day. I have loaded in my mat file which contains variables e.g wind(500x1), temp(500x1), waves(500x1). I have created a list of the variables in the mat file using who. What i want to do is use the list of files to select each variable in turn, interpolate it and then define a new variable. I can't seem to get the cell string created by who to identify the variable in the workspace.
Licor_Datetime and Und_Datetime(500x1) are just two time vectors. I have no issue with the interpolation.
Any help would be appreciated
Richard
load ('C:\Users\rps207\Documents\MATLAB\CO2 NSOP output analysis\Data\DY030underway.mat')
Varnames = who('-file','C:\Users\rps207\Documents\MATLAB\CO2 NSOP output analysis\Data\DY030underway.mat');
%
for i=1:numel(Varnames)
Varnames_new= interp1(Und_Datetime,Varnames(i),Licor_Datetime);
end
Basic solution with no loops, tedious for 50+ variables
Salinity_new= interp1(Und_Datetime,Varnames(i),Licor_Datetime);
Waves_new= interp1(Und_Datetime,Waves,Licor_Datetime);
Temperature_new= interp1(Und_Datetime,Temperature,Licor_Datetime);
  1 Comment
Stephen23
Stephen23 on 6 Jun 2016
@Richard Sims: Walter Roberson's answer is the best way to solve your question. In future you should keep in mind that it although it is possible to access variables like that, in practice it is very slow and buggy, and should be avoided. Here is an explanation of why you should not try to create or access lots of variable names dynamically:

Sign in to comment.

Accepted Answer

Walter Roberson
Walter Roberson on 3 Jun 2016
Assign the output of load() to a variable. The result will be a structure with one field for every variable in the .mat . If you want to check whether a particular variable is there you can use fieldnames() on the structure.
  1 Comment
Richard Sims
Richard Sims on 6 Jun 2016
Hi Walter, thanks for your answer, it send me down the right path. My code is now working! For completeness, here is the working code.
%load in the mat file
C=load ('C:\Users\rps207\Documents\MATLAB\CO2 NSOP outputanalysis\Data\DY030underway.mat')
%define list of variable using fieldnames
names=fieldnames(C)
%create new names for variables with _interp suffix
for t=1:numel(names)
rty=[names(t) '_interp'];x=horzcat(rty{:}) ;new_names(:,t)=cellstr(x);
end
% Interpolate variables in a loop using new variable names
%Output is a structure S containing all the new interpolated variables
for i=1:numel(names)
s.(new_names{i})=interp1(Und_DT,C.(names{i}),Licor_Datetime);;
end

Sign in to comment.

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!