Apply Function to a Variable in Timetable

조회 수: 1 (최근 30일)
Louise Wilson
Louise Wilson 2019년 5월 9일
편집: Steven Lord 2019년 5월 14일
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