9

I have a function with the following prototype

function [bandwidth,density,X,Y,x,y]=kde2d(data,n,MIN_XY,MAX_XY)

basically the function returns 6 outputs as above, some are in vector form while others are a numerical quantity. How can I elegantly pass the output from the function into a 1 by 6 cell array?

gamerx
  • 579
  • 5
  • 16

1 Answers1

13

how about

[a{1:6}] = kde2d( data, n, MIN_XY, MAX_XY )

Edit:

consider this annoying function

def foo(n):
  if n == 1:
    return [1, ]
  elif n == 2:
    return [1, ], {'a': 2}
  elif n == 3:
    return [1, ], {'a': 2}, (3, 3, 3)
  return [1, ], {'a': 2}, (3, 3, 3), None

You can always get all the outputs into a single tuple:

for i in range(1, 5):
  f = foo(i)
  print('got {} outputs: {}'.format(len(f), f))

and the output of this simple loop would be:

got 1 outputs: [1]
got 2 outputs: ([1], {'a': 2})
got 3 outputs: ([1], {'a': 2}, (3, 3, 3))
got 4 outputs: ([1], {'a': 2}, (3, 3, 3), None)

If you want to get a specific output:

f = foo(2)
f[1]   # accessing the second output, {'a': 2} in this example.
Shai
  • 111,146
  • 38
  • 238
  • 371
  • What if we don't know the number of the function's output? – M.Hossein Rahimi Jan 19 '20 at 14:28
  • 1
    @HosseinRahimi I think you can simply get the output into a single variable and then query its `len` – Shai Jan 19 '20 at 14:40
  • Assume we have a function named [out1, out2, out3, ...] = foo(). foo() could have any number of outputs from 1 to 10 (based on the input and the nargout). What I need to get all of the available outputs of the function, regardless of the input or. – M.Hossein Rahimi Jan 19 '20 at 14:49
  • For instance, with the method that you mentioned above, we have 3 possible scenarios, 1. if nargout==6: we get the first 6 outputs of out function 2. if nargout<6: we get an error saying not enough argout 3. if nargout>6: we won't get all of the outputs (nargout: number of arg out) – M.Hossein Rahimi Jan 19 '20 at 15:05