How do I create a vector with the first day of each month?

How do I create a column vector with the first day of each month? Considering I have a list of days...

댓글 수: 3

Jan
Jan 2013년 4월 27일
편집: Jan 2013년 4월 27일
Please explain what "I have a list of dates" exactly means. Guessing the type and size of the inputs would be an inefficient approach.
a list of days would be a column vector that goes from 10/01/1998 till 06/31/1999 in numbers
And example in valid Matlab syntax would be more helpful. The input is still not clear. Something like this would be much easier to understand:
data = [datenum('10/01/1998'), datenum('06/31/1999')]

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

 채택된 답변

John Doe
John Doe 2013년 4월 27일
편집: John Doe 2013년 4월 27일
Not quite sure what you are asking for here.
I assume you have a vector with all days from Monday-Sunday, and you know which day the first day of the year is:
weekdays = [{'Monday'},{'Tuesday'},{'Wednesday'},{'Thursday'},{'Friday'},{'Saturday'},{'Sunday'}];
dayNumber = zeros(1,12);
dayNumber(1) = 2; % 2013 started on a Tuesday.
numDays = [31 28 31 30 31 30 31 31 30 31 30 31]; % Not a leap year
for i = 1:11
dayNumber(i+1) = mod((dayNumber(i)+days(i)-1),7)+1;
end
for i = 1:12
dayName(i) = weekdays(dayNumber(i));
end
If you need to account for leap years: It is a leap year every fourth year, except years that can be divided by 100, except years that can be divided by 400.
A general approach would be something like this:
year = 2013;
year0 = 1900;
startDay = 1; % Year 1900 started on a monday.
if year > year0
for i = 1:(year-year0)
if mod((year0+i),4)~=0
startDay = startDay + 365;
elseif mod((year0+i),4)==0 && mod((year0+i),100)~=0
startDay = startDay + 366;
elseif mod((year0+i),4)==0 && mod((year0+i),100)==0 && mod((year0+i),400)~=0
startDay = startDay + 365;
elseif mod((year0+i),4)==1 && mod((year0+i),400)==0
startDay = startDay + 366;
end
end
end
dayNumber = mod(startDay,7)+1;
This gives dayNumber = 2, for year = 2013. Then continue with the code above. (numDays(2)=29, if leap year)

댓글 수: 2

thanks a lot!
@Robert: Nicer and more efficient:
weekdays = {'Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'};

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

추가 답변 (1개)

Jan
Jan 2013년 4월 27일
indata = datenum('10/01/1998'):datenum('06/31/1999');
dvec = datevec(data);
duniq = unique(dvec(:, 1:2), 'rows');
result = datenum(v(:,1), v(:,2), 1);
Now result contains a row vector of the serial date numbers of the first day of each month contained in the input data.

카테고리

도움말 센터File Exchange에서 Time Series Objects에 대해 자세히 알아보기

질문:

2013년 4월 27일

Community Treasure Hunt

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

Start Hunting!

Translated by