Effacer les filtres
Effacer les filtres

Apply Function to a Variable in Timetable

1 vue (au cours des 30 derniers jours)
Louise Wilson
Louise Wilson le 9 Mai 2019
Modifié(e) : Steven Lord le 14 Mai 2019
Hi everyone,
I have been using the 'rowfun' helpfile but I can't get this to work.
I am writing a matlab script to eventually apply to a large folder of .csv files.
The issue is here:
func = @(x) x.*-1;
data4=varfun(func,data3,'LATITUDE',3);
I want to multiply the entire column 'Latitude', which is the 3rd column in my data set, by -1.
Have I put this together correctly? All I want to do is make the values in this column negative.
Thanks in advance!
My full code:
dd = 'input_data';
nowd = cd;
d = dir('*.csv');
for j=1:length(d)
tic
filename=d(j).name;
disp(filename);
dat=readtable(filename);
data=table2timetable(dat, 'RowTimes', 'LOCALTIME'); %orientate timetable using 'localtime' as the time vector
try
fid = fopen(fullfile(dd,filename));
data2=removevars(data, [1 2 3 4 7 9 10]); %remove columns I am not interested in
data3=timetable2table(data2);
func = @(x) x.*-1;
data4=varfun(func,data3,'LATITUDE',3);
catch
disp('error');
fclose(filename);
end
end

Réponse acceptée

Steven Lord
Steven Lord le 9 Mai 2019
Modifié(e) : Steven Lord le 9 Mai 2019
I want to multiply the entire column 'Latitude', which is the 3rd column in my data set, by -1.
That's easy and doesn't require varfun. I'll make a sample table.
T = array2table(magic(4), 'VariableNames', ...
{'A', 'alpha', 'Longitude', 'Latitude'})
Now to operate on all of a variable in the table there are a number of ways to access that data. Simplest is:
T.Latitude = -T.Latitude
Alternately you can use numeric indices, but in that case you need to use curly brackets and need to keep track of which variable is in which position in the table. I'd prefer the approach above, as that's very expressive to anyone reading your code.
T{:, 4} = -T{:, 4}
  2 commentaires
Louise Wilson
Louise Wilson le 9 Mai 2019
Thanks Steven! I ended up doing this to get the same result. I guess this is SLIGHTLY different:
data_new.LATITUDE=data_new.LATITUDE.*-1;
Peter Perkins
Peter Perkins le 14 Mai 2019
Modifié(e) : Steven Lord le 14 Mai 2019
Steve answered this already, but just to answer the original question: I think you wanted
varfun(func,data3,'InputVariables','LATITUDE')
or
varfun(func,data3,'InputVariables',3)
[SL: removed an extra ' in the second block of code.]

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Produits


Version

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by