GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — subset of matrix should always return the same type (matrix) · Issue #2344 · josdejong/mathjs

subset of matrix should always return the same type (matrix) #2344

New issue
Copy link
New issue
Copy link
Closed
Closed
subset of matrix should always return the same type (matrix)#2344
Copy link
Labels
featurehelp wanted
Milestone
v15

Description

@petres
petres
opened on Oct 30, 2021
Issue body actions

Depending on the index the function subset returns a matrix or a scalar.
How can I set that the return type is always a matrix? Is there another function?

Activity

  1. josdejong commented on Nov 3, 2021

    @josdejong
    josdejong
    on Nov 3, 2021
    Owner
    More actions

    Have you tried the configuration option predictable?

  2. josdejong
    added
    question
    on Nov 3, 2021
  3. josdejong commented on Nov 3, 2021

    @josdejong
    josdejong
    on Nov 3, 2021
    Owner
    More actions

    I just tried it but I see predictable is not implemented there.

    so, what we would like is:

    math.config({ predictable: false })
    math.subset(math.matrix([1,2,3,4]), math.index(1)) // number 2
    
    math.config({ predictable: true })
    math.subset(math.matrix([1,2,3,4]), math.index(1)) // Matrix/Array containing one value 2

    Anyone interested in making subset adhere to the predictable config and always return a matrix in that case? Help would be welcome

  4. josdejong
    added
    feature
    help wanted
    and removed
    question
    on Nov 3, 2021
  5. petres commented on Nov 5, 2021

    @petres
    petres
    on Nov 5, 2021
    Author
    More actions

    subset should always return a Matrix. If the user wants to extract an element of that matrix he could use get. In the case he doesn't know about the returned dimensionality (because the param index is dynamic) she will always prefer to get the same type.

  6. josdejong commented on Nov 6, 2021

    @josdejong
    josdejong
    on Nov 6, 2021
    Owner
    More actions

    What "the user" wants depends on the use case and which user you're talking about 😄 .

    In a programmatic JavaScript environment it indeed makes sense to use two different, explicit methods get and subset, each giving back predictable results.

    The method subset (and the whole of mathjs) was originally created though for end users using the expression parser to do mathematics. It focuses on making it easy to work with matrices, and was heavily inspired by how you can work with matrices in mathematical applications like Matlab, Octave, Maple, Mathematica.

    So in the expression parser you do things like the following, where it is implicit whether you get back a value or a matrix:

    A = [1, 2; 3, 4]
    myvalue = A[1, 2]    # will return number 2
    mysubset = A[2, 1:2] # will return the second row [[3, 4]]
    

    You could argue to make an explicit API in the expression parser too, but this is how the mathematical world is used to work and it works like a charm.

    Similarly, a function like sqrt will normally return a complex result instead of a number with value NaN when you enter a negative value, like sqrt(-4). That makes the function unpredictable. In some cases like mathematical end users this is desirable, in other cases like programmatically using the function you want a predictable output type. That's why the configuration option predictable was introduced, and I think this issue will be addressed by extending subset to adhere to this config option.

  7. dvd101x commented on Jul 19, 2023

    @dvd101x
    dvd101x
    on Jul 19, 2023
    SponsorCollaborator
    More actions

    By checking other references I think the logic is more in line of the type of the input instead of the size of the index so that if every range in index comes from a scalar then it yields a scalar.

    A = [1, 2; 3, 4]
    A[1, 2]      # yields  2
    A[1, [2]]    # yields [2]
    A[[1], 2]    # yields [2]
    A[1:1, 2]    # yields [2]
    A[1, 2:2]    # yields [2]
    A[2, 1:2]    # yields [3, 4]
    A[[2], 1:2]  # yields [[3, 4]]

    I see also some differences on higher dimension arrays regarding if it comes from an array or comes from a range.

    Some of that shows promising capabilities but there is still utility in checking the size of the index.

    Reacted by Jos de Jong
  8. gwhitney commented on Jul 24, 2023

    @gwhitney
    gwhitney
    on Jul 24, 2023
    Collaborator
    More actions

    This issue came up in #2994, and I think there is a clear convention that could/should be adopted here that will eliminate any use of the "predictable" mechanism. That is to say, I would propose that indexing any dimension with a scalar eliminates that dimension, whereas indexing it with an array leaves that dimension in place, regardless of the length of the array. For example, if A =[1,2,3; 4,5,6] then (with 1-based indexing as in the parser):

    A[2,3]  --> 6
    A[[1,2],[2,3]] --> [2,3; 5,6]
    A[[2],[2,3]] --> [[5, 6]]
    A[2,[2,3]] --> [5,6]
    A[[1,2],[2]] --> [2; 5]  // which is the same as [[2], [5]]
    A[[1,2],2] --> [2,5]
    A[[2], [2]] --> [[5]]
    A[2, [2]] --> [5]
    A[[2], 2] --> [5]
    

    This way, the type of the result is exactly predictable just from the types of the indices; it's compatible with boolean indexing as recently implemented; and I believe it covers the original poster's use-case. Thoughts? The change from current behavior is that for example all three of the last expressions currently return just 5. Conceptually, it would not be the count of entries that determines the type of the result, but just the types of the indices.

    There are some edge cases with empty vectors for indices:

    A[1,[]] --> []  // Seems clear
    A[[],2] --> []  // Seems OK, no rows.
    A[[],[]] --> ??? // Seems like it should be 2-D, but it also seems like it should have no rows. Is there any distinction
    // between a 1-D and 2-D empty matrix in mathjs? Right now, I don't think so... There is [[]], but that seems to have one (empty) row, rather than being 2D but having no rows...
    

    but I think these things could be ironed out in some reasonable way, I don't think they detract from the basic proposal.

  9. josdejong commented on Jul 27, 2023

    @josdejong
    josdejong
    on Jul 27, 2023
    Owner
    More actions

    Ow, that is a great idea! I love it. It definitely makes sense to me.

  10. dvd101x commented on Jul 27, 2023

    @dvd101x
    dvd101x
    on Jul 27, 2023
    SponsorCollaborator
    More actions

    It also makes sense to me.

    As a reference for the edge cases, in numpy it would be like this:

    A[[],[]] --> []

    The same would apply for N dimensions:

    A[[],2,3]   --> []
    A[1,[],3]   --> []
    A[1,2,[]]   --> []
    A[1,[],[]]  --> []
    A[[],2,[]]  --> []
    A[[],[],3]  --> []
    A[[],[],[]] --> []
    Reacted by Jos de Jong
  11. gwhitney commented on Oct 6, 2023

    @gwhitney
    gwhitney
    on Oct 6, 2023
    Collaborator
    More actions

    This is actually a duplicate of the much older #1484, but since the discussion here is more in-depth, I'm actually going to close the older one.

    Reacted by Jos de Jong
  12. DbCrWk commented on Oct 6, 2023

    @DbCrWk
    DbCrWk
    on Oct 6, 2023
    More actions

    This is actually a duplicate of the much older #1484, but since the discussion here is more in-depth, I'm actually going to close the older one.

    I originally opened #1484, but didn’t get around to opening a PR. This resolution looks great!

  13. dvd101x commented on Apr 22, 2025

    @dvd101x
    dvd101x
    on Apr 22, 2025
    SponsorCollaborator
    More actions

    Hi, I would like to work on this.

    Reacted by Ethan Herdrick
  14. josdejong commented on Apr 22, 2025

    @josdejong
    josdejong
    on Apr 22, 2025
    Owner
    More actions

    👍 thanks David!

  15. herdrick commented on Apr 24, 2025

    @herdrick
    herdrick
    on Apr 24, 2025
    More actions

    I'm not sure if this is the correct place or time to discuss this, but the symmetry of getting and setting seems like a good goal. For example, for some matrix M, ex. M = [[1, 2], [3, 4]], if you set a slice to a vector:

    M[1, :] = [11, 22]

    ... then for my part, I would think that querying that slice should give the same vector. But instead it gives:

    M[1, :] --> [[11, 22]]

    Failing that, if the project is committed to M[1, :] --> [[11, 22]], then perhaps the setting should be M[1, :] = [[11, 22]]

  16. herdrick commented on Apr 24, 2025

    @herdrick
    herdrick
    on Apr 24, 2025
    More actions

    A second thought is that, again for a matrix M = [[1, 2], [3, 4]], since M[1] currently throws a DimensionError, why not specify that M[1] -> [1, 2] ? It looks like maybe this wouldn't collide with anything, but I haven't carefully looked in to it. It would be in line with "Indexing any dimension with a scalar eliminates that dimension". It would conform with the semantics of Numpy and MATLAB, and perhaps others, idk.

  17. gwhitney commented on Apr 24, 2025

    @gwhitney
    gwhitney
    on Apr 24, 2025
    Collaborator
    More actions

    I'm not sure if this is the correct place or time to discuss this, but the symmetry of getting and setting seems like a good goal. For example, for some matrix M, ex. M = [[1, 2], [3, 4]], if you set a slice to a vector:

    M[1, :] = [11, 22]

    ... then for my part, I would think that querying that slice should give the same vector. But instead it gives:

    M[1, :] --> [[11, 22]]

    Failing that, if the project is committed to M[1, :] --> [[11, 22]], then perhaps the setting should be M[1, :] = [[11, 22]]

    Sorry, I'm not following; I think the conclusion is that if A=[[1, 2], [3, 4]] then A[1, :] should be [1, 2], not [[1, 2]] as is currently returned. It just isn't implemented yet.

    As to your point about get-set symmetry, it's made murky by the fact that the source of the assignment is replicated as needed to fill the destination: After A=[1,2; 3,4; 5;6]; A[[2,3],:] = [7, 8] we have that A is [[1, 2], [7, 8], [7, 8]]. So the 1-dimensional row has been replicated to fill the 2-dimensional "hole" of the specified subset. I don't see much reason to abandon this setting convention, but it does mean that what can appear on the RHS of an assignment is pretty flexible, whereas of course getting a subset will just return one specific shape. Thus, with the mathjs conventions, we can't really rely on get-set symmetry as a guide.

    I also don't see a lot of motivation to allow M[1] when M is two-dimensional; it's reasonably likely to be a typo and to me it seems ambiguous between meaning M[1, :] and M[:, 1]. Not clear why one should be privileged over the other, especially when both are so convenient to write.

    Reacted by Ethan Herdrick
  18. herdrick commented on Apr 24, 2025

    @herdrick
    herdrick
    on Apr 24, 2025
    More actions

    I think the conclusion is that if A=[[1, 2], [3, 4]] then A[1, :] should be [1, 2], not [[1, 2]] as is currently returned. It just isn't implemented yet.

    Oh I'm sorry, I didn't realize that was the conclusion. So that takes care of my concern about get-set symmetry because the new getting functionality will line up with the setting in that simpler sort of case I mentioned, and also negates the utility of my suggestion about M[1]! 👍

  19. dvd101x commented on Apr 25, 2025

    @dvd101x
    dvd101x
    on Apr 25, 2025
    SponsorCollaborator
    More actions

    While working on it I noticed that if the index includes scalars, they get transformed to immutableDensseMatrices which makes them indistinguishable from each other from the methods toString and toJSON which will make it difficult to use Index.fromJSON to get the same functionality than the index that was exported to JSON.

    const indexWithScalars = new math.Index(1, 2)
    const indexWithArrays = new math.Index([1], [2])
    
    math.deepEqual(indexWithScalars, indexWithArrays)  // true
    indexWithScalars.toString() === indexWithArrays.toString() //true
    math.deepEqual(
                   indexWithScalars.toJSON().dimensions,
                   indexWithArrays.toJSON().dimensions
                   ) // true

    This will be a breaking change regardless (due to the slicing), but I'm thinking on the following options that will affect the scope of the PR.

    Option 1:

    Keep the internal _dimensions

    Internally new Index(1, 1)._dimensions are ImmutableDenseMatrix of size [1] so, keep them as they are.

    [
        {
            "mathjs": "ImmutableDenseMatrix",
            "data": [
                1
            ],
            "size": [
                1
            ]
        },
        {
            "mathjs": "ImmutableDenseMatrix",
            "data": [
                1
            ],
            "size": [
                1
            ]
        }
    ]

    For which a property indicating if the _dimensions came from a scalar (an array of booleans) could be added, and then tweak the methods .toString, .toJSON and .fromJSON to convert back those ImmutableDenseMatrix as scalars as needed.

    Option 2

    Change the internal representation to scalars, so new Index(1, 1)._dimensions would be.

    [1, 1]

    For which some other methods will need to be tweaked, as they depend on the matrix methods, but probably will save some time from the costly matrix creation for simple scalars.

    Option 3

    Change also the non scalar representations

    Currently number, bigint, array, array of booleans, matrix and matrix of booleans are converted to ImmutableDenseMatrix. But maybe most of them can be simpler like:

    • maintain string, Range, number, array as they are
    • convert bigint to number
    • convert matrix to array

    Summary

    I would like to know how much could the internal representation of the indices/ranges be changed. Maybe I'm overlooking the importance of the immutability of ImmutableDenseMatrix

  20. josdejong commented on Apr 26, 2025

    @josdejong
    josdejong
    on Apr 26, 2025
    Owner
    More actions

    I guess math.Index normalizes scalar inputs into arrays, so it always only has to deal with arrays. If we now need to know whether the index originally had a scalar value or not, we have to make changes. At first sight, I think Option 2 would be most neat, but I'm not sure how much impact it will have on other methods.

    Reacted by David Contreras
  21. gwhitney commented on Apr 26, 2025

    @gwhitney
    gwhitney
    on Apr 26, 2025
    Collaborator
    More actions

    I agree, the internal representation of an Index should be totally irrelevant to the outside world, so you should have a free hand to use whatever representation is best suited to the task at hand. If immutability is important, you can make Index objects immutable in any of a few different ways as appropriate: by having its interface entirely consist of getters, by Object.freeze()ing them before you give them back, or by returning Proxy objects that trap and deny any set actions. There may even be other ways.

    Reacted by David Contreras
  22. dvd101x commented on Apr 27, 2025

    @dvd101x
    dvd101x
    on Apr 27, 2025
    SponsorCollaborator
    More actions

    Thanks Jos and Glen for your insights. Will take them into account in the next steps.

  23. dvd101x commented on May 30, 2025

    @dvd101x
    dvd101x
    on May 30, 2025
    SponsorCollaborator
    More actions

    Hi, just to report some progress

    Option 2 seems to work.

    https://github.com/josdejong/mathjs/tree/matrix-subset-according-to-type-of-input

    Still haven't changed the behaviour of the subset, but changed the index so that it maintains the scalar and doesn't convert to a matrix

  24. josdejong commented on May 30, 2025

    @josdejong
    josdejong
    on May 30, 2025
    Owner
    More actions

    Thanks for the update David, this looks promising already 👍.

    Reacted by David Contreras
  25. josdejong
    added this to the v15 milestone on Jun 4, 2025
  26. josdejong commented on Jul 16, 2025

    @josdejong
    josdejong
    on Jul 16, 2025
    Owner
    More actions

    Implemented via #3485.

    Reacted by Peter Reschenhofer and David Contreras
    Reacted by David Contreras
  27. josdejong
    closed this as completedon Jul 16, 2025
  28. josdejong commented on Oct 10, 2025

    @josdejong
    josdejong
    on Oct 10, 2025
    Owner
    More actions

    Published now in v15.0.0.

    Reacted by Peter Reschenhofer
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    featurehelp wanted

    Type

    No type

    Projects

    No projects

      Milestone

      • v15No due date

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions

      You are visitor 01402792 — GeezerVison does not store the pages you look up.
      Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.