How to set a variable name in a code

조회 수: 1 (최근 30일)
gianluca
gianluca 2014년 4월 10일
답변: Jos (10584) 2014년 4월 10일
Hi, I'm writing a code to make operations on imported external data coming from several measurement sites and plot results. I would write a code in a general form for further applications. The name of the site changes and then also the name of the variable, where the data are stored, changes.
% this simple code imports external data, filters them and plots the results
fid = fopen('ALCAMOLOG.csv');
alcamo = importdata('ALCAMOLOG.csv');
alcamo.data(alcamo.data == -999.25) = NaN;
alcamo_smoothed = struct('DEPTH',{alcamo.data(:,1)},...
'SP',{sgolayfilt(alcamo.data(:,2), 3, 71)},...
'GR',{sgolayfilt(alcamo.data(:,3), 3, 71)},...
'SN',{sgolayfilt(alcamo.data(:,4), 3, 71)},...
'LN',{sgolayfilt(alcamo.data(:,5), 3, 71)},...
'DT',{sgolayfilt(alcamo.data(:,6), 3, 71)},...
'RHOB',{sgolayfilt(alcamo.data(:,7), 3, 71)},...
'NEUT',{sgolayfilt(alcamo.data(:,8), 3, 71)});
figure(2); subplot(1,6,1);
plot(alcamo_smoothed.SP, alcamo_smoothed.DEPTH(:,1),'k-');
grid on; box on; xlabel([alcamo.colheaders{1,2}]); ylabel([alcamo.colheaders{1,1}]);
set(gca,'YDir','reverse');
As you see the word "alcamo" compares several time (I'm operating on this specific site). How can I write this code in a more general form so that when I import new data from another site and a different site name is set, I haven't to change in the code the word "alcamo" by hand to run correctly the code, i.e.:
fid = fopen('PIPPOLOG.csv');
pippo = importdata('PIPPOLOG.csv');
pippo.data(pippo.data == -999.25) = NaN;
pippo_smoothed = struct('DEPTH',{pippo.data(:,1)},...
'SP',{sgolayfilt(pippo.data(:,2), 3, 71)},...
'GR',{sgolayfilt(pippo.data(:,3), 3, 71)},...
'SN',{sgolayfilt(pippo.data(:,4), 3, 71)},...
'LN',{sgolayfilt(pippo.data(:,5), 3, 71)},...
and so on! A solution could be don't use in the code the site name and use a more general name always valid. Then, to work in a separate folder for each site. This is the simplest solution, but I would solve this issue in programming language. Any advice? Regards, Gianluca

채택된 답변

Jos (10584)
Jos (10584) 2014년 4월 10일
Do not use variable names for variables. It is the content of a variable that should change, not its name!
filename = 'pippo' ; % you only have to change this!
% this is the same for all files
D = importdata([filename '.csv']);
D.OriginalFilename = filename ; % for later use
D(D.data==999) = NaN ;
D.SmoothData = struct ( . . . etc . . )
save([filename '_processed.mat'],'D')

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 2-D and 3-D Plots에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by