function ndx = sub2ind_ignoreBounds(siz,v1,v2,varargin)
%SUB2IND Linear index from multiple subscripts.
%   See SUB2IND.

%   Author: The MathWorks, Inc., modified by Damien Teney

siz = double(siz);
lensiz = length(siz);
if lensiz < 2
    error(message('MATLAB:sub2ind:InvalidSize'));
end

numOfIndInput = nargin-1;
if lensiz < numOfIndInput
    %Adjust for trailing singleton dimensions
    siz = [siz, ones(1,numOfIndInput-lensiz)];
elseif lensiz > numOfIndInput
    %Adjust for linear indexing on last element
    siz = [siz(1:numOfIndInput-1), prod(siz(numOfIndInput:end))];
end

if any(min(v1(:)) < 1) || any(max(v1(:)) > siz(1))
    %Verify subscripts are within range
    error(message('MATLAB:sub2ind:IndexOutOfRange'));
end

invalid = false(length(v1), 1); % Marks invalid (out of bound) inputs

ndx = double(v1);
s = size(v1);
if numOfIndInput >= 2
    if ~isequal(s,size(v2))
        %Verify sizes of subscripts
        error(message('MATLAB:sub2ind:SubscriptVectorSize'));
    end
    invalid = invalid | (v2(:) < 1) | (v2(:) > siz(2)) ;
    %Compute linear indices
    ndx = ndx + (double(v2) - 1).*siz(1);
end 
    
if numOfIndInput > 2
    %Compute linear indices
    k = cumprod(siz);
    for i = 3:numOfIndInput
        v = varargin{i-2};
        %%Input checking
        if ~isequal(s,size(v))
            %Verify sizes of subscripts
            error(message('MATLAB:sub2ind:SubscriptVectorSize'));
        end
        invalid = invalid | (v(:) < 1) | (v(:) > siz(i)) ;
        ndx = ndx + (double(v)-1) * k(i-1);
    end
end

ndx(invalid) = NaN; % Default value for invalid indices
