Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the point of the deal() function in Octave / MATLAB?

Tags:

matlab

octave

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...

  • conventionally stylistic or idiomatic, in place of simple assignment like 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?
  • useful for some more elegant feature -- e.g., "deep" versus "shallow" copy, if such a concept even exists here, if 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.

like image 895
hoc_age Avatar asked Jan 11 '23 10:01

hoc_age


1 Answers

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.

like image 107
Sam Roberts Avatar answered Jan 20 '23 12:01

Sam Roberts