Azzera filtri
Azzera filtri

Apply Function to a Variable in Timetable

1 visualizzazione (ultimi 30 giorni)
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

Risposta accettata

Steven Lord
Steven Lord il 9 Mag 2019
Modificato: Steven Lord il 9 Mag 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 Commenti
Louise Wilson
Louise Wilson il 9 Mag 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 il 14 Mag 2019
Modificato: Steven Lord il 14 Mag 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.]

Accedi per commentare.

Più risposte (0)

Categorie

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

Prodotti


Release

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by