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

3 vues (au cours des 30 derniers jours)
alpedhuez
alpedhuez le 18 Juin 2020
Commenté : alpedhuez le 18 Juin 2020
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 commentaires
Rik
Rik le 18 Juin 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.
alpedhuez
alpedhuez le 18 Juin 2020
using strcmp

Connectez-vous pour commenter.

Réponse acceptée

Ameer Hamza
Ameer Hamza le 18 Juin 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));

Plus de réponses (0)

Catégories

En savoir plus sur Cell Arrays dans Help Center et File Exchange

Tags

Produits


Version

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by