0

I am trying to figure out this substring feature and whether there exists a function call for it or not. As far as I can find, here and here along with various other places, there simply is no related function for this since strings are char arrays, and so they settled for only implementing the indexing feature.

MWE:

fileID = fopen('tryMe.env');
outDate = fgetl(fileID);

Where the file 'tryMe.env' only consists of 1 line like so:

2014/9/4

My wanted result is:

outDate = 
    '14/9/4'

I am trying to find a clean, smooth one liner to go with the variable definition of outDate, something along the lines of outDate = fgetl(fileID)(3:end);, and not several lines of code.

Thank you for your time!

Community
  • 1
  • 1
Tubbles
  • 59
  • 4
  • This is possible, but I have to ask: Why can't you live with two lines? – Stewie Griffin Sep 24 '14 at 06:13
  • http://stackoverflow.com/questions/3627107/how-can-i-index-a-matlab-array-returned-by-a-function-without-first-assigning-it – Cheery Sep 24 '14 at 06:17
  • I guess I am used to too much C, and simply cherish minimal but functional and readable code. I guess with the answer posted in Cheery's link, two lines solution is a bit more handsome. Thank you – Tubbles Sep 24 '14 at 06:25
  • try `outDate = datestr( datenum ( fgetl( fopen('tryMe.txt') ) ) , 'yy/mm/dd')` for a one liner ... but you still will have to close the file after, and i'm not sure about 'readability' on some one liners. – Hoki Sep 24 '14 at 07:20

1 Answers1

1

For the specific example you gave, seems like

outDate=textscan(fileID, '%*2c%infc')

would do what you want ( skip 2 characters, then read until end of line).

If you are trying to read a date, which you will later want to manipulate as a date, like comparing, differencing, etc, you could also use datenum on your fgetl line. Or, if you want a normalized date string, For instance

outDate=datestr(datenum(fgetl(fileID)),'yy/mm/dd')

would produce the string '14/09/04'

JonB
  • 350
  • 1
  • 7
  • Yes thank you, it would seem that your first example is what I was looking for since I need to handle the input as nothing but strings – Tubbles Sep 24 '14 at 08:33