Reversing a list in Excel within a formula

前端 未结 4 774
刺人心
刺人心 2020-12-16 06:55

So there are a bunch of ways to reverse a list to turn it into a new list, using helper columns. I\'ve written some code that does use helper columns to reverse a list and t

4条回答
  •  借酒劲吻你
    2020-12-16 07:22

    For what it's worth, here's another completely different method to reverse an array. (I'm posting this as a separate answer just because it is apples and oranges to the other answer I already provided.)

    Instead of reversing the order of the array by reversing the indexing, it is also possible to use matrix multiplication (MMULT) to accomplish this.

    If your data in A1:A3 is {1;3;5} (for example) then the following matrix multiplication effectively reverses this array:

    [0 0 1]   [1]   [5]
    [0 1 0] * [3] = [3]
    [1 0 0]   [5]   [1]
    

    In order to generate that matrix of 1's and 0's above, you can do this (line break added for readability):

    = (ROW(INDEX(A:A,1):INDEX(A:A,ROWS(A1:A3)))=
      (COLUMN(INDEX(1:1,ROWS(A1:A3)))-COLUMN(INDEX(1:1,1):INDEX(1:1,ROWS(A1:A3)))+1))+0
    

    So in the end, the formula to reverse this array would be:

    = MMULT((ROW(INDEX(A:A,1):INDEX(A:A,ROWS(A1:A3)))=
      (COLUMN(INDEX(1:1,ROWS(A1:A3)))-COLUMN(INDEX(1:1,1):INDEX(1:1,ROWS(A1:A3)))+1))+0,A1:A3)
    

    This same line of thinking can be used to reverse a horizontal array. For example if A1:C1 is {1,3,5}, then:

              [0 0 1]
    [1 3 5] * [0 1 0] = [5 3 1]
              [1 0 0]
    

    Note how the matrix of 1's and 0's is the second argument this time instead of the first argument.

    Using the same general line of reasoning, you can get to this formula to reverse a horizontal array.

    = MMULT(A1:C1,(ROW(INDEX(A:A,1):INDEX(A:A,COLUMNS(A1:C1)))=
      (COLUMN(INDEX(1:1,COLUMNS(A1:C1)))-COLUMN(INDEX(1:1,1):INDEX(1:1,COLUMNS(A1:C1)))+1))+0)
    

    This method has two major disadvantages as compared two the N(IF(...)) solution, namely:

    1. It's way longer.

    2. It only works for numbers since MMULT requires numbers, but the other method works if the cells contain anything (e.g. text).

    I was using this solution to reverse arrays without helper columns until just recently when I learned about the N(IF(...)) alternative.

提交回复
热议问题