Some reference code uses the function deal()
trivially, like
[a, b, c] = deal (1,2,3)
As described in the documentation (for Octave and for MATLAB), the function simply copies the inputs to the outputs. Why use deal()
in this case, or even in general? I'm trying to learn "more correct" MATLAB/Octave usage, and wondering if I'm missing something significant. Perhaps, is this usage...
a=1, b=2, c=3
or the more arcane list-unpacking of cell-arrays like [a,b,c] = {1,2,3}{:}
, but even more restricted than Python argument unpacking, like in this question?deal()
were used with complicated/variable arguments?I also understand single-argument [a,b,c]=deal(42)
but that's essentially a=b=c=42
, and [a,b,c]=deal(x)
assigns x
to all, not elements-of-x
to each.
Or perhaps it's ONLY that I'm over-thinking this trivial use of the function.
One really useful way that I occasionally use deal
is to create anonymous functions that return multiple output arguments. For example,
>> f = @(x) deal(x^2,x^3);
>> [a,b] = f(3)
a =
9
b =
27
Edit since people seem to find this pattern potentially useful, do note a quirk, in that you must return the full number of outputs. In particular, you can't use a = f(3)
, or it will error. To retrieve just a single output, use [a,~] = f(3)
or [~,b] = f(3)
. The ~
syntax for suppressing output arguments has been around since about R2007a or so (I'm afraid I can't recall exactly when) - in older versions, you will need to always return both outputs. Hope that may be useful for you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With