Search code examples
octaveoctave-gui

Problems with sub2ind function in Octave


I am new to Octave, so I was reading documentation and I found sub2ind function. I started to test it, but sometimes it works weird or I just don't understand how it must work.

So this is how subscripts must be converted to linear indices. (Example from documentation)

[(1,1), (1,2), (1,3)]     [1, 4, 7]
[(2,1), (2,2), (2,3)] ==> [2, 5, 8]
[(3,1), (3,2), (3,3)]     [3, 6, 9]

And this is another example from documentation

s1 = [2, 2];
s2 = [1, 3];
ind = sub2ind ([3, 3], s1, s2)
    ⇒ ind =  2   8 

So if we look at the first example the (2, 2) == 5, but second example says [2, 2] == 2. The (1, 3) has different results too. Practically It works as the second example shows.

If I try to use this function with only 1 pair it return the same pair

sub2ind([3, 3], [2, 2])
# ans = [2, 2]

In this test I can't see any relation between input and output

sub2ind([3, 3], [2, 2], [3, 3])
# ans = [8, 8]

Function works this strange(maybe not) way only when it gets 1 pair or when one of pairs is pair kind [x, x](two same values).

But otherwise it works fine, so this test returns that it should:

sub2ind([3, 3], [2, 1], [1, 3])
# ans = [2, 7]

Also it works fine when this variant is used sub2ind (dims, i, j). How does the function works?


Solution

  • You misunderstand the input format.

    Change

    s1 = [2, 2];
    s2 = [1, 3];
    ind = sub2ind ([3, 3], s1, s2)
        ⇒ ind =  2   8
    

    to this:

    row = [2, 2];  % x1 and x2
    col = [1, 3];  % y1 and y2
    ind = sub2ind ([3, 3], row, col)
        ⇒ ind =  2   8
    

    You have two inputs that you convert to linear indices: [x1, y1] = [2, 1] = 2 and [x2 y2] = [2, 3] = 8.


    This:

    sub2ind([3, 3], [2, 2])
    # ans = [2, 2]
    

    appears to be equivalent to:

    sub2ind([3, 3], [2, 2], [1, 1])
    

    even though it's not in the documentation.