1// Scilab ( http://www.scilab.org/ )
2// Copyright (C) INRIA - Serge STEER
3//
4
5function I=sub2ind(dims,varargin)
6//sub2ind is used to determine the equivalent single index
7//corresponding to a given set of subscript values.
8
9//I = sub2ind(dims,i1,i2,..) returns the linear index equivalent to the
10//row,  column, ... subscripts in the arrays i1,i2,..  for an matrix of
11//size dims.
12
13//I = sub2ind(dims,Mi) returns the linear index
14//equivalent to the n subscripts in the columns of the matrix Mi for a matrix
15//of size dims.
16
17  d=[1;cumprod(matrix(dims(1:$-1),-1,1))]
18  for i=1:size(varargin)
19    if varargin(i)==[] then I=[],return,end
20  end
21
22  if size(varargin)==1 then //subindices are the columns of the argument
23    I=(varargin(1)-1)*d+1
24  else //subindices are given as separated arguments
25    I=1
26    for i=1:size(varargin)
27      I=I+(varargin(i)-1)*d(i)
28    end
29  end
30endfunction
31