Search code examples
arraysstringmatlabdatedisp

How to display the dates from a column separately?


I have a set of data such that column 1 shows the date (in MATLAB serial number form) and column 2 shows the rainfall, as shown like this:

x = [ 22029   81 
      23040   90.2
      26701   90.2
      28223  188
      36973   92
      38386   99.8
      40580  117.8];

So far the code I have is:

out = x(x(:,2) > 180,:,1); %gets all the dates with rainfall greater than 180
out2 = x(x(:,2) > 80,:,1); %gets all the dates with rainfall greater than 80
c1 = out(:,1);
c2 = out2(:,1);
rain = datestr(c1); %converts from MATLAB serial number to date
rain2 = datestr(c2); %converts from MATLAB serial number to date
X = sprintf('Heaviest rainfall will occur on %s.',rain);
X2 = sprintf('Heavy rainfall will occur on %s.',rain2);
disp(X)
disp(X2) 

My disp(X) works and displays:

Heaviest rainfall will occur on 08-Apr-0077.

However my disp(X2) does not work and displays

Heavy rainfall will occur on 22002003968447-------AJFAMFFpaepaeernbrrbb-------0000000000011166770010337151.

How do I fix my code for disp(X2) so that it shows:

Heavy rainfall will occur on 23-Apr-0060, 29-Jan-0063, 06-Feb-0073, 08-Apr-0077, 24-Mar-0101, 04-Feb-0105, 04-Feb-0105.

Solution

  • This is happening because matrices are stored in column major order in MATLAB. You can reorder your Rain2 character array before using the sprintf function as follows:

    rain2(:,end+1) = ',';     rain2(end) = '.';   %For , in between and . at the end
    rain2 = rain2.';  %Reordering
    X2 = sprintf('Heavy rainfall will occur on %s', rain2);
    

    Result:

    >> X2
    X2 =
        'Heavy rainfall will occur on 23-Apr-0060,29-Jan-0063,06-Feb-0073,08-Apr-0077,24-Mar-0101,04-Feb-0105,07-Feb-0111.'