Reassign Categorical Variable Value

5 views (last 30 days)
Marko Rajkovic
Marko Rajkovic on 15 Oct 2019
Answered: Peter Perkins on 30 Oct 2019
Hello everyone,
I built a 7647×2 Table with Variables "td" for Trading week-day and "close" for the closing prices of the Swiss Market Index, where td is Categorical and close Double
The Market is open only from Monday to Friday, but the td variable summary displays some "Sunday" observation. I checked on the Calendar and those are actually either Mondays or Fridays.
Is there I way I can replace all Sundays with the appropriate Day? I tried with the following:
for i = 1:length(td);
for td(i) == 'Sunday'; %for all Sundays in the Sample
if td(i+1) == 'Monday'
td(i) == 'Friday' %change to friday if the following day is monday
elseif td(i+1) == 'Tuesday'
td(i) == 'Monday' %change to monday if the following day is tuesday
end
end;
end;
But I am a mess with for loops and if statements and I am not really sure how to use them with categorical variables
Anyone could help?

Answers (1)

Peter Perkins
Peter Perkins on 30 Oct 2019
If you wanted to all the sundays into mondays, it would be easy: combinecats. But you want to turn them into either mondays or fridays depending on whether they are followed by a monday or a tuesday. Right?
You should be able to do this without loops:
i1 = (t.td(1:end-1) == 'Sunday') && (t.td(2:end) == 'Monday');
t.td(i1) = 'Friday';
i2 = (t.td(1:end-1) == 'Sunday') && (t.td(2:end) == 'Tuesday');
t.td(i2) = 'Monday';
t.td = removecats(t.td); % drop the now unused Sunday

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!