MATLAB: Apply Function to a Variable in Timetable

for loopforloopMATLABrowfun

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

Best Answer

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}
Related Question