Apply Function to a Variable in Timetable

1 次查看(过去 30 天)
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

采纳的回答

Steven Lord
Steven Lord 2019-5-9
编辑:Steven Lord 2019-5-9
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 个评论
Louise Wilson
Louise Wilson 2019-5-9
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 2019-5-14
编辑:Steven Lord 2019-5-14
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.]

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品


版本

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by