User Defined Function to Add Fields to Table

조회 수: 1 (최근 30일)
Rachel McLaughlin
Rachel McLaughlin 2016년 5월 3일
댓글: Rachel McLaughlin 2016년 5월 4일
Hi all, I am a matlab beginner and am trying to create a user defined function that will take the "Date" column of a table, split it into 3 new columns (Day/Month/Year), and add them to the input table. I do not know if this is possible as a function. Currently I have it set up as:
function [] = splitdate(x)
%Turns dates into a serial number
Date= datenum(x.Date);
%Creates variable for Time stamps
Time= x.Time;
%Concatenates date and time entries into serial datetime numbers.
DateTime= Date + Time;
%Add fields to table for Day/Month/Year
DateVec= datevec(DateTime); %takes serial date numbers and makes column vectors
x.Day = DateVec(:, 3);
x.Month = DateVec(:,2);
x.Year = DateVec(:, 1);
It might be that I am trying to do too much with one function, but any feedback would be helpful. x would be whatever name was assigned for the table that was read in using readtable.
Thanks
  댓글 수: 2
CS Researcher
CS Researcher 2016년 5월 3일
Can you give an example of the input x?
Rachel McLaughlin
Rachel McLaughlin 2016년 5월 4일
The input x would be a table read in from an excel file using
filename= 'spreadsheet.xlsx'; Table= readtable(filename, 'Sheet', 1);

댓글을 달려면 로그인하십시오.

채택된 답변

Walter Roberson
Walter Roberson 2016년 5월 3일
It is possible as a function. However, remember that most things are passed into functions by value, not by reference, so if you want to change something that is an input parameter, you need to return the new version of it from the function and the calling routine needs to assign it on top of the old variable.
function x = splitdate(x)
...
with the caller doing
MyTable = splitdate(MyTable); %same name on input and output.
  댓글 수: 1
Rachel McLaughlin
Rachel McLaughlin 2016년 5월 4일
Excellent! Thank you very much! I had figured it had something to do with my function output but wasn't sure how to make it work.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Dates and Time에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by