简体   繁体   中英

Iterating numbers within a string (Matlab)

In Matlab I am trying to achieve the following:

I need to provide an end date, which I would like to iterate forward by quarter in the format: '1970q1' For this I have made a loop.

for yy=1970:1971
    for jj=1:4
        fprintf('''%dq%d''',(yy),(jj))        
    end
end

However, when I set enddate=fprintf

for yy=1970:1971
    for jj=1:4
        enddate=fprintf('''%dq%d''',(yy),(jj))        
    end
end

within the loop, it does not store the end date as what the fprintf output is, but something else. The way the end date should be stored is: enddate='1970q1'

You should use sprintf function for creating strings instead of fprintf that writes text to file.

In your case, if you want to save all the enddate values you should save it in a vector:

enddate = [];
for yy=1970:1971
    for jj=1:4
        enddate=[enddate sprintf('''%dq%d''',(yy),(jj))];      
    end
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM