diff --git a/libinterp/corefcn/sub2ind.cc b/libinterp/corefcn/sub2ind.cc --- a/libinterp/corefcn/sub2ind.cc +++ b/libinterp/corefcn/sub2ind.cc @@ -264,12 +264,24 @@ r = ind2sub (dims, ind) octave_value_list retval; - // Redimension to provided number of subscripts. + int nd = nargout == 0 ? 1 : nargout; + dim_vector dv = get_dim_vector (args(0), "ind2sub").redim (nargout); + // Redim for 1 will give us a column vector but we want a row. + if (nd == 1) + { + int tmp = dv(0); + dv(0) = dv(1); + dv(1) = tmp; + } + try { retval = Array (ind2sub (dv, args(1).index_vector ())); + + if (nd == 1) + retval(0) = retval(1); } catch (const index_exception& ie) { diff --git a/liboctave/array/Array-util.cc b/liboctave/array/Array-util.cc --- a/liboctave/array/Array-util.cc +++ b/liboctave/array/Array-util.cc @@ -623,17 +623,21 @@ ind2sub (const dim_vector& dv, const oct Array retval (dim_vector (n, 1)); octave_idx_type numel = dv.numel (); +#if 0 if (idx.extent (numel) > numel) (*current_liboctave_error_handler) ("ind2sub: index out of range"); +#endif if (idx.is_scalar ()) { octave_idx_type k = idx(0); - for (octave_idx_type j = 0; j < n; j++) + for (octave_idx_type j = 0; j < n-1; j++) { retval(j) = k % dv(j); k /= dv(j); } + + retval(n-1) = idx(0) < numel ? k % dv(n-1) : k; } else { @@ -646,11 +650,13 @@ ind2sub (const dim_vector& dv, const oct for (octave_idx_type i = 0; i < len; i++) { octave_idx_type k = idx(i); - for (octave_idx_type j = 0; j < n; j++) + for (octave_idx_type j = 0; j < n-1; j++) { rdata[j](i) = k % dv(j); k /= dv(j); } + + rdata[n-1](i) = idx(i) < numel ? k % dv(n-1) : k; } for (octave_idx_type j = 0; j < n; j++)