Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>There is no operator in MATLAB that will do that. However, if your indices (i.e. <code>bar</code> in your example) were stored in a <a href="https://www.mathworks.com/help/matlab/cell-arrays.html" rel="nofollow noreferrer">cell array</a>, then you could do this:</p> <pre><code>bar = {3,4,5}; %# Cell array instead of standard array foo(bar{:}); %# Pass the contents of each cell as a separate argument </code></pre> <p>The <code>{:}</code> creates a <a href="https://www.mathworks.com/help/matlab/matlab_prog/comma-separated-lists.html" rel="nofollow noreferrer">comma-separated list</a> from a cell array. That's probably the closest thing you can get to the "operator" form you have in your example, aside from overriding one of the <a href="https://www.mathworks.com/help/matlab/matlab_oop/implementing-operators-for-your-class.html" rel="nofollow noreferrer">existing operators</a> (illustrated <a href="https://stackoverflow.com/q/7577802/52738">here</a> and <a href="https://stackoverflow.com/q/5365464/52738">here</a>) so that it generates a comma-separated list from a standard array, or creating your own class to store your indices and defining how the existing operators operate for it (neither option for the faint of heart!).</p> <p>For your specific example of indexing an arbitrary N-D array, you could also compute a linear index from your subscripted indices using the <a href="https://www.mathworks.com/help/matlab/ref/sub2ind.html" rel="nofollow noreferrer"><code>sub2ind</code></a> function (as detailed <a href="https://stackoverflow.com/q/5904488/52738">here</a> and <a href="https://stackoverflow.com/q/792683/52738">here</a>), but you might end up doing more work than you would for my comma-separated list solution above. Another alternative is to <a href="https://stackoverflow.com/q/1146719/52738">compute the linear index yourself</a>, which would sidestep <a href="https://www.mathworks.com/help/matlab/ref/num2cell.html" rel="nofollow noreferrer">converting to a cell array</a> and use only matrix/vector operations. Here's an example:</p> <pre><code>% 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) </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload