问题
How does one generate an array according to value in cells? For example, if (A1,B1) is (3,0), (A2,B2) is (2,1), and (A3,B3) is (2,0) (this first number depicts how many of the second number in the array), how does one obtain an array of {0,0,0,1,1,0,0}? In a general form, if I have (i,0), (j,1), and (k,0), I would like to get an array of {i zeros,j ones, k zeros}.
Several Excel functions can return an array, such as OFFSET, INDEX. I don't know any way to concatenate arrays.
Any way to do this?
回答1:
If you step through this with Evaluate Formula, you should see that it generates an array as requested:
=SUM(INDEX(B:B,N(IF({1},MATCH(ROW(A1:INDEX(A:A,SUM(A:A))),IFERROR(SUBTOTAL(9,OFFSET(A1,0,0,ROW(A1:INDEX(A:A,COUNT(A:A)))-1,1))+1,1),1)))))
must be entered with CtrlShiftEnter
Basically it uses offset and subtotal to generate an array containing a running total of the values in column A, then uses match and index to lookup numbers from 1 to 7 in this array and find the corresponding number in column B. Not very elegant because I had to use an offset with a height of zero to get the first value in the lookup array, then iferror to set the resulting #REF! to 1.
It's a separate question of how to concatenate such an array - if you have Excel 2019 or 365 you can use Textjoin.
EDIT
If you wish to avoid using volatile functions like Offset, you can get the running totals of column A another way, by developing a 2d array as follows and using Mmult:
0 0 0
1 0 0
1 1 0
Formula:
=SUM(INDEX(B:B,N(IF({1},MATCH(ROW(A1:INDEX(A:A,SUM(A:A))),
MMULT(IF(ROW(A1:INDEX($1:$1048576,COUNT(A:A),COUNT(A:A)))>COLUMN(A1:INDEX($1:$1048576,COUNT(A:A),COUNT(A:A))),1,0),
A1:INDEX(A:A,COUNT(A:A)))+1)))))
回答2:
Assume your data housed in A1:B3
as in :
A B
3 0
2 1
2 0
In D1
, enter formula :
=LOOKUP(ROW(INDIRECT("1:"&SUM(A1:A10))),IFERROR(SUMIF(OFFSET(A$1,,,ROW(A1:A10)-1),"<>")+1,1),B1:B3)
Highlight D1
, press keystroke F9 and cell D1
will give an array result :
={0;0;0;1;1;0;0}
来源:https://stackoverflow.com/questions/59226903/generate-an-array-of-0-and-1-with-given-conditions