function [sub] = ind2subm(sze, idx)
% sub = ind2subm(sze, idx)
% Multiple subscripts from linear indices.
% Similar to matlabs built-in function, but returns an array of subscripts. Each column are the subscripts for one index.
% XX Function is very slow and should be vectorized
%
% Input:
%   sze         Size of the array
%   idx         linear indices to be converted
%
% Output:
%   sub         array, each column are the subscripts for the corresponding indices in idx
%
% E.g.:
%
% See also: ind2subm([2 1 3],[1 6])
%
% Written by tommsch, 2017 

lensze= length(sze);
lenidx=length(idx);

sub=zeros(lensze, lenidx);
k = [1 cumprod(sze)];
if(any(idx>k(end)) || any(idx<1)); error('Index out of bounds.'); end;

for j=1:lenidx
    val=idx(j)-1; %compute for zero based indexing
    for i = lensze:-1:1;
        sub(i,j)=fix(val/k(i));
        val=val-sub(i,j)*k(i);
    end
    sub(:,j)=sub(:,j)+1; %go back to 1-based indexing
end

end

function dummy; end %#ok<DEFNU> %Generates an error, if the 'end' of a function is missing.


