Since MATLAB Release R2007a, you've been able to number the arguments for functions that format strings. With this feature, you can refer to the values that correspond to the different arguments in a varying order. So what mischief can we get up to?
Contents
Possible Uses
There are at least two cases I can think of where being able to refer to specific arguments by position can be useful.
- Translation
This can be important to users writing code for broad use, where some of the output might need to be written in different languages or the language the output is written in depends on the locale. Not all languages express certain ideas in the same way, and this may necessitate using the arguments in a different order depending on the output language (sort of like cochon jaune in French vs. yellow pig in English).
- Argument reuse
There are cases in which you might want to reuse an argument when writing out a string (perhaps a string of code or html). Here's a case where we want to have a string and its value match each other; the radio button label is the actual value.
optionName = 'Case'; optionValue = 'Ignore'; s = sprintf(... '<input type=radio name="%1$s" value="%2$s"/>%2$s\n', ... optionName, optionValue)
s = <input type=radio name="Case" value="Ignore"/>Ignore
References
Here are some MATLAB references for formatting strings.
- Documentation for Formatting Strings - Note especially the section on restrictions for using the ordered identifiers.
- R2007a Release Notes
- See the help for these related functions: sprintf, fprintf, error, warning, assert
Other Uses?
Can you think of cases where you would take advantage of this? Post them here so we can see them!
Get
the MATLAB code
Published with MATLAB® 7.5



Loren,
I have a question about colon notation that is not covered in doc colon. Why does 1:A, where A is a matrix, evaluate to 1:A(1)? This seems to be an important gotcha because if you try to evaluate
A=1:50;
1:50-A
You’ll get an answer equal to 1:49, rather than the more intuitive zeros(size(A)).
–Raymond
Raymond:
It appears that the - has priority over the :. Try (1:50)-A to get what you expected.
Loren:
That is a nice trick. Not that I will probably ever use it, but still. I would personally say that the obfuscation caused by the longer code sequences in the text do not outweigh the added benefit of being able to reorder or repeat arguments, ignoring the translation case which I will not have to deal with in the near or even remote future.
–DA
Loren: Oh, I just noticed I got my negations wrong. I think you still understand what I mean, though.
19+7 ~= 29 september
where r u Loren?
% —————-
u can find several function or operetor who ussed 1st argument.
function myfunc()
fzero(@(y,x) mysubfunc(y,2),2)
fzero(@(y,x) mysubfunc(2,x),2)
function f = mysubfunc(y,x)
f =x+y+1;