Looping through list of files to access variable names

5 visualizzazioni (ultimi 30 giorni)
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 Commento
Stephen23
Stephen23 il 6 Giu 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:

Accedi per commentare.

Risposta accettata

Walter Roberson
Walter Roberson il 3 Giu 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 Commento
Richard Sims
Richard Sims il 6 Giu 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

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by