14
votes

I want to splice a vector into a function call, but I can't find a way to do this. Is it possible?

To expand on what I mean, say we have the vector x of length n and a function f that takes n arguments. I want to be able to call f(x(1), x(2), ..., x(n)) by calling something like f(x) or f(splice(x)). If x were a cell array instead of a vector, calling f(x{:}) would get the desired result; it only seems reasonable that there would be some equivalent for when x is a vector.

I'm hoping for some operator or function that I'm missing. I could just call y = num2cell(x) followed by f(y{:}), but this is not really what I'm looking for.

1
Doesn't x(:) work? Or if it's a column vector use x(:)'.Thor
The num2cell route is exactly what you should be looking for.Jonas
@Jonas Fair enough, in that that solution is simple. But I think that it's a bit silly that I have to specify a temporary variable (and, thus, have the variable's contents copied an extra time) just to do this. Why would this feature exist for cell arrays but not for the (arguably more common) numeric array (i.e., the "mat" in "matlab")? Anyhow, that's why I was asking: It just seemed like a feature that is likely supported but that I was somehow missing.zroth
@Thor No, that does not work. Regardless of the shape of x, x(:) is always a column vector. In particular, if x is already a vector, then x(:) is just the same vector (though perhaps transposed).zroth
Have you tried deal?tmpearce

1 Answers

7
votes

As already mentioned in the comments

tmp = num2cell(x)
f(tmp{:})

is the way to go.

A function splice so that f(splice(x)) would do what you want, doesn't do the trick. Even if you can split the input into multiple outputs, f only takes the first argument (similarly to if you were to call the function at command line without requesting outputs).

Not even subsref will work in this case, since e.g. subsref(num2cell([1 2]),struct('type','{}','subs',{{':'}})) is going to do the same as the splice-function, i.e. only return one output unless multiple outputs have been requested explicitly.