How to interpolate on categorical data

I need to interpolate data. For floating point numbers, I usually use

interp1(given_time,given_data,uniform_time)

      

However, in this case, my given_data

is a cell of an array of strings:

time=[1,5,18,30,40,42,47,54,64]

season=[{'winter'},{'winter'},{'winter'}, {'spring'}, {'spring'}, {'spring'}, {'summer'}, {'summer'}, {'summer'} ]

uniform_time=1:5:64

uniform_season= ????

      

Each output cell should be a string according to the nearest value uniform_time

How do I implement it in Matlab?

If uniform_time(i)

there is exactly between time(j)

and time(k)

permissible or value season(j)

, or season(k)

.

In the above case, I expect to get:

uniform_season= [{'winter'}, {'winter'}, {'winter'}, {'winter'}, {'winter'}, {'spring'}, {'spring'}, {'spring'}, {'spring/summer'}, {'summer'}, {'summer'}, {'summer'}, {'summer'}]

      

by {'spring/summer'}

I mean either {'spring'}

or {'summer'}

, but not both {'spring/summer'}

.

I calculated it according to this table:

new data: 1 6   11  16  21  26  31  36  41  46  51  56  61
closest old data: 1 5   18  18  18  30  30  40  41/42   47  54  54  64
string of old data: 'winter'    'winter'    'winter'    'winter'    'winter'    'spring'    'spring'    'spring'    spring/summer'  'summer'    'summer'    'summer'    'summer'

      

+3


source to share


1 answer


Try the following:



%// Inputs:
time=[1,5,18,30,40,42,47,54,64]
season=[{'winter'},{'winter'},{'winter'}, {'spring'}, {'spring'}, {'spring'}, {'summer'}, {'summer'}, {'summer'} ]
uniform_time=1:5:64

%// Change season to an ordinal list
[season_unique,~,season_int] = unique(season, 'stable')
idx = interp1(time, season_int, uniform_time, 'nearest-neighbour') %// Good chance you'll want to add the 'extrap' flag here as well
season_unique(idx)

      

+2


source







All Articles