1

I'v read and re-read the help about the function sprintf in matlab but I do not understand everything about this function and the format they talk about.

I was asking myself the logic behind the function formats.

If I run the example

sprintf('%05d%s%02d%s%02d',546,'.',1,'.',3)

I get

00546.01.03

which is logic, since the first number (546) is written as an integer and with 5 digits, the second is a character, and so on... But if now I try this

sprintf('%05d%s%02d%s%02d',546,'.',1,'.',3,4)

I get

00546.01.0300004

the first part is the same as above... But the last part of it (00004) has the format '%05d', that corresponds to the first format I entered in the function's arguments. My question is then Does the first format become the 'default' format ?

By trying this

sprintf('%05d%s%02d%s%02d',546,'.',1,'.',3,4,56)

and getting this

00546.01.03000048

I think the answer is no... But why ? And what is then the logic behind those arguments?

Thanks for your help !

1
  • 2
    Or could it be that it forms a sort of loop ? Commented Jul 10, 2013 at 10:45

1 Answer 1

3

You are providing sprintf more arguments than there are %s in the format string. Therefore, sprintf re-uses the format string from begining:

sprintf('%05d%s%02d%s%02d',546,'.',1,'.',3,4,56)

result:

00546.01.03000048
         ^  
         starting fromat anew printing 00004 for %05d with 4   

The final '8' character is 56 printed as '%s' (if you want to check it out the ascii code of '8' (the char) is 56!)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.