Does Matlab have a splat operator (or equivalent)?

If I have an array (of unknown length to runtime), is there a way to call a function with each element of the array as a separate parameter?

Same:

foo = @(varargin) sum(cell2mat(varargin)); bar = [3,4,5]; foo(*bar) == foo(3,4,5) 

Context: I have a list of indexes for an array of n -d, Q I want something like Q(a,b,:) , but I only have [a,b] . Since I do not know n , I cannot just code the indexing.

+6
source share
1 answer

There is no operator in MATLAB that does this. However, if your indexes (i.e. bar in your example) were stored in an array , then you can do this:

 bar = {3,4,5}; %# Cell array instead of standard array foo(bar{:}); %# Pass the contents of each cell as a separate argument 

{:} creates a comma separated list from an array of cells. This is probably the closest thing you can get in the form of an β€œoperator” that you have in your example, except that it does not overlap one of the existing operators (illustrated here and here ) so that it generates a comma-separated list from a standard array or created your own class to store your indexes and determine how existing operators work (not an option for the faint of heart!).

For your specific example of indexing an arbitrary ND array, you can also calculate a linear index from your indexed indices using sub2ind functions (as described here and here below), but you can end up doing more work than for my comma-separated solution to the list above. Another alternative is to compute the linear index yourself , which will skip the conversion to an array of cells and use only matrix / vector operations. Here is an example:

 % Precompute these somewhere: scale = cumprod(size(Q)).'; %' scale = [1; scale(1:end-1)]; shift = [0 ones(1, ndims(Q)-1)]; % Then compute a linear index like this: indices = [3 4 5]; linearIndex = (indices-shift)*scale; Q(linearIndex) % Equivalent to Q(3,4,5) 
+7
source

Source: https://habr.com/ru/post/905750/


All Articles