Return subscripts of a variable dimension matrix

后端 未结 1 1456
耶瑟儿~
耶瑟儿~ 2021-01-15 13:54

I need to be able to return the indices [x1 x2 ... xd] of the elements of a matrix of dimensions LxLxL..xL. The number of dimensions d is a variable supplied to my function.

相关标签:
1条回答
  • 2021-01-15 14:48

    I assume by "the indices [x1 x2 ... xd]" you mean the subscripts along each dimension of the equivalent d-dimensional array.

    You need to convert L and d to a dimension array, and then capture multiple argouts from ind2sub. Here's a function that does so. You can call it like x = myind2sub(L, d, i).

    function out = myind2sub(L, d, ix)
    
    sz = repmat(L, [1 d]); %// dimension array for a d-dimension array L long on each side
    c = cell([1 d]);  %// dynamically sized varargout
    [c{:}] = ind2sub(sz, ix);
    out = [c{:}];
    

    But you should also ask why you're storing it in a linear array and calculating subscripts, instead of just storing it in a multidimensional array in the first place. In Matlab, a multidimensional array is stored in a contiguous block of memory, so it's efficient, and you can index in to it using either multidimensional subscripts or linear indexing. If you have a linear array, just call reshape(myarray, sz) to convert it to the multidimensional equivalent.

    0 讨论(0)
提交回复
热议问题