Search code examples
arraysmatlabindices

How to pull specific indices out of a character array in a loop?


I have an array that contains multiple dates in the format yyyymmdd, stored as a 50x1 double. I am trying to pull out the year,month, and day so I can use datenum to assign each date a serial number.

Indexing an individual date, converting the using str2num, then indexing and pulling the appropriate values works fine, but when I try to loop through the list of dates it doesn't work- only variations of the number 2 are returned.

dates = [20180910; 20180920; 20181012; 20181027; 20181103; 20181130; 20181225];

% version1
datesnums=num2str(dates); % dates is a list of dates stored as 
integers

for i=1:length(datesnums)
    pullyy=str2num(datesnums(1:4));
    pullmm=str2num(datesnums(5:6));
    pulldd=str2num(datesnums(7:8));
end

As well as

%version2
datesnums=num2str(dates,'%d')

for i = 1:length(datesnums)
    dd=datenum(str2num(datesnums(i(1:4))),str2num(datesnums(i(5:6))), 
    str2num(datesnums(i(7:8))));
end

I'm trying to generate a new array that is just the serial numbers of the input dates. In the examples shown, I am only getting single integer values, which I know is because the loop is incorrect and I get errors that say "Index exceeds the number of array elements (1)." for version 1. When I've gotten it to successfully loop through everything, the outputs are just '2222','22,'22' for every single date which is incorrect. What am I doing wrong? Do I need to incorporate a cell array?


Solution

  • To get all the years, month, and days in a loop:

    datesnums=num2str(dates);
    
    for i=1:size(datesnums, 1)
        pullyy(i) = str2num(datesnums(i,1:4));
        pullmm(i) = str2num(datesnums(i,5:6));
        pulldd(i) = str2num(datesnums(i,7:8));
    end
    

    Actually, you can do this without a loop:

    pullyy = str2num(datesnums(:,1:4));
    pullmm = str2num(datesnums(:,5:6));
    pulldd = str2num(datesnums(:,7:8));
    

    Explanation:

    If for example the dates vector is a [6x1] array:

    dates =[...
        20190901
        20170124
        20191215
        20130609
        20141104
        20190328];
    

    Than datesnums=num2str(dates); creates a char matrix of size [6x8] where each row corresponds to one element in dates:

    datesnums =
    
      6×8 char array
    
        '20190901'
        '20170124'
        '20191215'
        '20160609'
        '20191104'
        '20190328'
    

    So in the loop you need to refer to the row index for each date and and the column indices to extract the years, month, and days.