开发者

Why does the following string to number conversion fail in Matlab?

开发者 https://www.devze.com 2023-03-05 11:32 出处:网络
I\'m trying to break up the date and add a single number to the day, month and year date = input(\'Please enter the date (DD/MM/YYYY):\',\'s\')

I'm trying to break up the date and add a single number to the day, month and year

date = input('Please enter the date (DD/MM/YYYY):','s')
开发者_如何学编程

tokens = regexp(sprintf(date),'/','split')
daymonthyear = str2num(tokens)
test = daymonthyear + 1


As the error message indicates, str2num expects strings, not a cell array of strings. There are two ways to solve the issue. Either, you can use str2double, or cellfun combined with str2num.

Solution 1

daymonthyear = str2double(tokens)

Solution 2

daymonthyear = cellfun(@str2num,tokens)


Jonas already addressed the specific error you were getting, but I thought you may be interested in a simpler approach that uses SSCANF instead of REGEXP:

date = input('Please enter the date (DD/MM/YYYY):','s');
daymonthyear = sscanf(date,'%d/%d/%d',[1 3]);


You can't do it using addtodate?

i = input('Please enter the date (DD/MM/YYYY):','s')
date = datenum(i, 'dd/mm/yyyy')
date = addtodate(date, 1, 'year')
date = addtodate(date, 1, 'month')
date = addtodate(date, 1, 'day')
tokens = regexp(datestr(date, 'dd/mm/yyyy'),'/','split')
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号