X
PrevPrev Go to previous topic
NextNext Go to next topic
Last Post 09 Mar 2018 01:16 AM by  Stefano Bianchi
One-item array and scalar
 2 Replies
Sort:
You are not authorized to post a reply.
Author Messages

Stefano Bianchi



New Member


Posts:5
New Member


--
08 Mar 2018 07:32 AM
    Hi,

    this is probably a naive question, but I can't find the solution.
    A simple example is the easiest way to present the issue.

    IDL> v1=[1,2,3,4,5]
    IDL> v2=[10,20,30,40,50]
    IDL> match=where(v1 eq 2)
    IDL> help, v2[match]
    <Expression> INT = Array[1]
    IDL> match2=v2[where(v1 eq 2)]
    IDL> help, match2[0]
    <Expression> INT = 20

    The problem is that v2[match] is, as expected, an array with only one item. However, this may cause different issues if used as it were a scalar (some of the issues are not very clear to me, to be honest, but some procedures fail to work, expecting a scalar, and others have different behaviours). The only solution I found is by using match2[0], as in the example, which is indeed a scalar. However, this does not seem to me an elegant solution, and it has the drawback that, if I have other arrays where I could use the same index resulting in match, in this way I should repeat for each of it the 'where' statement, instead of using always the first result.

    Is there an easier and more direct way to have immediately one scalar instead of a one-item array?

    Thanks,

    Stefano

    David Starbuck



    Basic Member


    Posts:143
    Basic Member


    --
    08 Mar 2018 12:54 PM
    A scalar variable can be treated as a 1-D array. Therefore, I think that in most cases, I think that indexing using 0, (for example scalar[0] or singleElementArray[0]) is probably the best solution. In a situation where you have a 1-D array, this will create a scalar. If you have a scalar, it won't cause any syntax issues. For example:

    IDL> a = 2L
    IDL> help, a
    A LONG = 2
    IDL> a
    2
    IDL> a[0]
    2
    IDL> a[-1]
    2

    David
    -HGS

    Stefano Bianchi



    New Member


    Posts:5
    New Member


    --
    09 Mar 2018 01:16 AM
    Thanks David, this is a possible solution.
    I was also suggested to use this syntax:

    w0=(where(v1 eq 2))[0]

    which is, in practice, what I was looking for.

    Stefano
    You are not authorized to post a reply.