How to define a new variable in a table, Part 2

3 views (last 30 days)
Suppose I have a table 'test' such as
month
-------
January
February
...
I now want to define a string variable 'season' such that
'season'='winter' if 'month' is 'January', 'February', or 'March'
etc. The output would be
month season
---- ---
January winter
February winter
...
Please advise.
  2 Comments
Rik
Rik on 18 Jun 2020
I don't work with tables myself, but a rowfun would probably do the trick. Just write a function that looks up the season for every moth (use ismember).
Note that this swaps for people in the southern hemisphere.

Sign in to comment.

Accepted Answer

Ameer Hamza
Ameer Hamza on 18 Jun 2020
Try this
T = % you table
Months = {'January', 'February', 'March', 'April', 'May', 'June', ...
'July', 'August', 'September', 'October', 'November', 'December'}.';
Mnth2Season = [1 1 1 2 2 2 3 3 3 4 4 4].'; % for example
Seasons = {'Winter', 'Spring', 'Summer', 'Autumn'}.';
[~, idx] = ismember(T.Months, Months);
T.Season = Seasons(Mnth2Season(idx));

More Answers (0)

Categories

Find more on Cell Arrays in Help Center and File Exchange

Tags

Products


Release

R2020a

Community Treasure Hunt

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

Start Hunting!