How to efficiently unroll a matrix by value with numpy? The 2019 Stack Overflow Developer Survey Results Are InHow to create mask with one at specified index?How to merge two dictionaries in a single expression?How do I check if a list is empty?How do I check whether a file exists without exceptions?How do I check if an array includes an object in JavaScript?How to append something to an array?How do I sort a dictionary by value?How do I determine whether an array contains a particular value in Java?How do I list all files of a directory?How do I remove a particular element from an array in JavaScript?How to use foreach with array in JavaScript?

Can an undergraduate be advised by a professor who is very far away?

Does adding complexity mean a more secure cipher?

I am an eight letter word. What am I?

Star Trek - X-shaped Item on Regula/Orbital Office Starbases

What do these terms in Caesar's Gallic Wars mean?

How much of the clove should I use when using big garlic heads?

Why couldn't they take pictures of a closer black hole?

Can withdrawing asylum be illegal?

Can we generate random numbers using irrational numbers like π and e?

Is an up-to-date browser secure on an out-of-date OS?

How can I add encounters in the Lost Mine of Phandelver campaign without giving PCs too much XP?

Is it okay to consider publishing in my first year of PhD?

Ubuntu Server install with full GUI

Inverse Relationship Between Precision and Recall

What do hard-Brexiteers want with respect to the Irish border?

Mathematics of imaging the black hole

For what reasons would an animal species NOT cross a *horizontal* land bridge?

How did passengers keep warm on sail ships?

How to type a long/em dash `—`

How to obtain a position of last non-zero element

Worn-tile Scrabble

What does Linus Torvalds mean when he says that Git "never ever" tracks a file?

Are there any other methods to apply to solving simultaneous equations?

Why didn't the Event Horizon Telescope team mention Sagittarius A*?



How to efficiently unroll a matrix by value with numpy?



The 2019 Stack Overflow Developer Survey Results Are InHow to create mask with one at specified index?How to merge two dictionaries in a single expression?How do I check if a list is empty?How do I check whether a file exists without exceptions?How do I check if an array includes an object in JavaScript?How to append something to an array?How do I sort a dictionary by value?How do I determine whether an array contains a particular value in Java?How do I list all files of a directory?How do I remove a particular element from an array in JavaScript?How to use foreach with array in JavaScript?



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








7















I have a matrix M with values 0 through N within it. I'd like to unroll this matrix to create a new matrix A where each submatrix A[i, :, :] represents whether or not M == i.



The solution below uses a loop.



# Example Setup
import numpy as np

np.random.seed(0)
N = 5
M = np.random.randint(0, N, size=(5,5))

# Solution with Loop
A = np.zeros((N, M.shape[0], M.shape[1]))
for i in range(N):
A[i, :, :] = M == i


This yields:



M
array([[4, 0, 3, 3, 3],
[1, 3, 2, 4, 0],
[0, 4, 2, 1, 0],
[1, 1, 0, 1, 4],
[3, 0, 3, 0, 2]])

M.shape
# (5, 5)


A
array([[[0, 1, 0, 0, 0],
[0, 0, 0, 0, 1],
[1, 0, 0, 0, 1],
[0, 0, 1, 0, 0],
[0, 1, 0, 1, 0]],
...
[[1, 0, 0, 0, 0],
[0, 0, 0, 1, 0],
[0, 1, 0, 0, 0],
[0, 0, 0, 0, 1],
[0, 0, 0, 0, 0]]])

A.shape
# (5, 5, 5)


Is there a faster way, or a way to do it in a single numpy operation?










share|improve this question
























  • It would be better if you explain it in detail.

    – Marios Nikolaou
    Apr 5 at 22:16






  • 2





    @MariosNikolaou just copy/paste his code and print(M);print(A)...I edited it for you though

    – Reedinationer
    Apr 5 at 22:18












  • @Reedinationer i did it.

    – Marios Nikolaou
    Apr 5 at 22:21











  • I would not recommend pasting output for this code as the input is randomised without a seed.

    – coldspeed
    Apr 5 at 22:21






  • 1





    i == M compare int with array 5x5 ? and then save it in A?

    – Marios Nikolaou
    Apr 5 at 22:26

















7















I have a matrix M with values 0 through N within it. I'd like to unroll this matrix to create a new matrix A where each submatrix A[i, :, :] represents whether or not M == i.



The solution below uses a loop.



# Example Setup
import numpy as np

np.random.seed(0)
N = 5
M = np.random.randint(0, N, size=(5,5))

# Solution with Loop
A = np.zeros((N, M.shape[0], M.shape[1]))
for i in range(N):
A[i, :, :] = M == i


This yields:



M
array([[4, 0, 3, 3, 3],
[1, 3, 2, 4, 0],
[0, 4, 2, 1, 0],
[1, 1, 0, 1, 4],
[3, 0, 3, 0, 2]])

M.shape
# (5, 5)


A
array([[[0, 1, 0, 0, 0],
[0, 0, 0, 0, 1],
[1, 0, 0, 0, 1],
[0, 0, 1, 0, 0],
[0, 1, 0, 1, 0]],
...
[[1, 0, 0, 0, 0],
[0, 0, 0, 1, 0],
[0, 1, 0, 0, 0],
[0, 0, 0, 0, 1],
[0, 0, 0, 0, 0]]])

A.shape
# (5, 5, 5)


Is there a faster way, or a way to do it in a single numpy operation?










share|improve this question
























  • It would be better if you explain it in detail.

    – Marios Nikolaou
    Apr 5 at 22:16






  • 2





    @MariosNikolaou just copy/paste his code and print(M);print(A)...I edited it for you though

    – Reedinationer
    Apr 5 at 22:18












  • @Reedinationer i did it.

    – Marios Nikolaou
    Apr 5 at 22:21











  • I would not recommend pasting output for this code as the input is randomised without a seed.

    – coldspeed
    Apr 5 at 22:21






  • 1





    i == M compare int with array 5x5 ? and then save it in A?

    – Marios Nikolaou
    Apr 5 at 22:26













7












7








7








I have a matrix M with values 0 through N within it. I'd like to unroll this matrix to create a new matrix A where each submatrix A[i, :, :] represents whether or not M == i.



The solution below uses a loop.



# Example Setup
import numpy as np

np.random.seed(0)
N = 5
M = np.random.randint(0, N, size=(5,5))

# Solution with Loop
A = np.zeros((N, M.shape[0], M.shape[1]))
for i in range(N):
A[i, :, :] = M == i


This yields:



M
array([[4, 0, 3, 3, 3],
[1, 3, 2, 4, 0],
[0, 4, 2, 1, 0],
[1, 1, 0, 1, 4],
[3, 0, 3, 0, 2]])

M.shape
# (5, 5)


A
array([[[0, 1, 0, 0, 0],
[0, 0, 0, 0, 1],
[1, 0, 0, 0, 1],
[0, 0, 1, 0, 0],
[0, 1, 0, 1, 0]],
...
[[1, 0, 0, 0, 0],
[0, 0, 0, 1, 0],
[0, 1, 0, 0, 0],
[0, 0, 0, 0, 1],
[0, 0, 0, 0, 0]]])

A.shape
# (5, 5, 5)


Is there a faster way, or a way to do it in a single numpy operation?










share|improve this question
















I have a matrix M with values 0 through N within it. I'd like to unroll this matrix to create a new matrix A where each submatrix A[i, :, :] represents whether or not M == i.



The solution below uses a loop.



# Example Setup
import numpy as np

np.random.seed(0)
N = 5
M = np.random.randint(0, N, size=(5,5))

# Solution with Loop
A = np.zeros((N, M.shape[0], M.shape[1]))
for i in range(N):
A[i, :, :] = M == i


This yields:



M
array([[4, 0, 3, 3, 3],
[1, 3, 2, 4, 0],
[0, 4, 2, 1, 0],
[1, 1, 0, 1, 4],
[3, 0, 3, 0, 2]])

M.shape
# (5, 5)


A
array([[[0, 1, 0, 0, 0],
[0, 0, 0, 0, 1],
[1, 0, 0, 0, 1],
[0, 0, 1, 0, 0],
[0, 1, 0, 1, 0]],
...
[[1, 0, 0, 0, 0],
[0, 0, 0, 1, 0],
[0, 1, 0, 0, 0],
[0, 0, 0, 0, 1],
[0, 0, 0, 0, 0]]])

A.shape
# (5, 5, 5)


Is there a faster way, or a way to do it in a single numpy operation?







python arrays numpy






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Apr 5 at 22:24









coldspeed

141k25157245




141k25157245










asked Apr 5 at 22:06









seveibarseveibar

1,31411225




1,31411225












  • It would be better if you explain it in detail.

    – Marios Nikolaou
    Apr 5 at 22:16






  • 2





    @MariosNikolaou just copy/paste his code and print(M);print(A)...I edited it for you though

    – Reedinationer
    Apr 5 at 22:18












  • @Reedinationer i did it.

    – Marios Nikolaou
    Apr 5 at 22:21











  • I would not recommend pasting output for this code as the input is randomised without a seed.

    – coldspeed
    Apr 5 at 22:21






  • 1





    i == M compare int with array 5x5 ? and then save it in A?

    – Marios Nikolaou
    Apr 5 at 22:26

















  • It would be better if you explain it in detail.

    – Marios Nikolaou
    Apr 5 at 22:16






  • 2





    @MariosNikolaou just copy/paste his code and print(M);print(A)...I edited it for you though

    – Reedinationer
    Apr 5 at 22:18












  • @Reedinationer i did it.

    – Marios Nikolaou
    Apr 5 at 22:21











  • I would not recommend pasting output for this code as the input is randomised without a seed.

    – coldspeed
    Apr 5 at 22:21






  • 1





    i == M compare int with array 5x5 ? and then save it in A?

    – Marios Nikolaou
    Apr 5 at 22:26
















It would be better if you explain it in detail.

– Marios Nikolaou
Apr 5 at 22:16





It would be better if you explain it in detail.

– Marios Nikolaou
Apr 5 at 22:16




2




2





@MariosNikolaou just copy/paste his code and print(M);print(A)...I edited it for you though

– Reedinationer
Apr 5 at 22:18






@MariosNikolaou just copy/paste his code and print(M);print(A)...I edited it for you though

– Reedinationer
Apr 5 at 22:18














@Reedinationer i did it.

– Marios Nikolaou
Apr 5 at 22:21





@Reedinationer i did it.

– Marios Nikolaou
Apr 5 at 22:21













I would not recommend pasting output for this code as the input is randomised without a seed.

– coldspeed
Apr 5 at 22:21





I would not recommend pasting output for this code as the input is randomised without a seed.

– coldspeed
Apr 5 at 22:21




1




1





i == M compare int with array 5x5 ? and then save it in A?

– Marios Nikolaou
Apr 5 at 22:26





i == M compare int with array 5x5 ? and then save it in A?

– Marios Nikolaou
Apr 5 at 22:26












3 Answers
3






active

oldest

votes


















6














Broadcasted comparison is your friend:



B = (M[None, :] == np.arange(N)[:, None, None]).view(np.int8)

np.array_equal(A, B)
# True


The idea is to expand the dimensions in such a way that the comparison can be broadcasted in the manner desired.




As pointed out by @Alex Riley in the comments, you can use np.equal.outer to avoid having to do the indexing stuff yourself,



B = np.equal.outer(np.arange(N), M).view(np.int8)

np.array_equal(A, B)
# True





share|improve this answer




















  • 1





    Good answer - just to point out there's a superfluous newaxis in your indexing for M (resulting in a 4D array). You could use M[None, :] instead to get the 3D array. An alternative to avoid fiddly indexing is to use np.equal.outer(np.arange(N), M).view(np.int8).

    – Alex Riley
    Apr 5 at 22:34












  • @AlexRiley Thanks for that! And the outer solution is quite neat.

    – coldspeed
    Apr 5 at 22:45


















6














You can make use of some broadcasting here:



P = np.arange(N)
Y = np.broadcast_to(P[:, None], M.shape)
T = np.equal(M, Y[:, None]).astype(int)



Alternative using indices:



X, Y = np.indices(M.shape)
Z = np.equal(M, X[:, None]).astype(int)





share|improve this answer

























  • This answer was really helpful towards my understanding of broadcasting, thank you!

    – seveibar
    Apr 6 at 0:58


















3














You can index into the identity matrix like so



 A = np.identity(N, int)[:, M]


or so



 A = np.identity(N, int)[M.T].T


Or use the new (v1.15.0) put_along_axis



A = np.zeros((N,5,5), int)
np.put_along_axis(A, M[None], 1, 0)


Note if N is much larger than 5 then creating an NxN identity matrix may be considered wasteful. We can mitigate this using stride tricks:



def read_only_identity(N, dtype=float):
z = np.zeros(2*N-1, dtype)
s, = z.strides
z[N-1] = 1
return np.lib.stride_tricks.as_strided(z[N-1:], (N, N), (-s, s))





share|improve this answer




















  • 1





    This is great, really interesting answer.

    – user3483203
    Apr 5 at 23:47






  • 1





    Hi Paul, this answer is really elegant, but the identity answers seem specific to the case where the N=M.shape[0]=M.shape[1]. Is the solution similarly elegant for N=/=M.shape[0]=/=M.shape[1]? Thanks for the answer, learning a lot!

    – seveibar
    Apr 6 at 0:55






  • 1





    @seveibar I've updated the answer. It is really just a matter of replacing the correct 5s with Ns.

    – Paul Panzer
    Apr 6 at 1:13











Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55543949%2fhow-to-efficiently-unroll-a-matrix-by-value-with-numpy%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























3 Answers
3






active

oldest

votes








3 Answers
3






active

oldest

votes









active

oldest

votes






active

oldest

votes









6














Broadcasted comparison is your friend:



B = (M[None, :] == np.arange(N)[:, None, None]).view(np.int8)

np.array_equal(A, B)
# True


The idea is to expand the dimensions in such a way that the comparison can be broadcasted in the manner desired.




As pointed out by @Alex Riley in the comments, you can use np.equal.outer to avoid having to do the indexing stuff yourself,



B = np.equal.outer(np.arange(N), M).view(np.int8)

np.array_equal(A, B)
# True





share|improve this answer




















  • 1





    Good answer - just to point out there's a superfluous newaxis in your indexing for M (resulting in a 4D array). You could use M[None, :] instead to get the 3D array. An alternative to avoid fiddly indexing is to use np.equal.outer(np.arange(N), M).view(np.int8).

    – Alex Riley
    Apr 5 at 22:34












  • @AlexRiley Thanks for that! And the outer solution is quite neat.

    – coldspeed
    Apr 5 at 22:45















6














Broadcasted comparison is your friend:



B = (M[None, :] == np.arange(N)[:, None, None]).view(np.int8)

np.array_equal(A, B)
# True


The idea is to expand the dimensions in such a way that the comparison can be broadcasted in the manner desired.




As pointed out by @Alex Riley in the comments, you can use np.equal.outer to avoid having to do the indexing stuff yourself,



B = np.equal.outer(np.arange(N), M).view(np.int8)

np.array_equal(A, B)
# True





share|improve this answer




















  • 1





    Good answer - just to point out there's a superfluous newaxis in your indexing for M (resulting in a 4D array). You could use M[None, :] instead to get the 3D array. An alternative to avoid fiddly indexing is to use np.equal.outer(np.arange(N), M).view(np.int8).

    – Alex Riley
    Apr 5 at 22:34












  • @AlexRiley Thanks for that! And the outer solution is quite neat.

    – coldspeed
    Apr 5 at 22:45













6












6








6







Broadcasted comparison is your friend:



B = (M[None, :] == np.arange(N)[:, None, None]).view(np.int8)

np.array_equal(A, B)
# True


The idea is to expand the dimensions in such a way that the comparison can be broadcasted in the manner desired.




As pointed out by @Alex Riley in the comments, you can use np.equal.outer to avoid having to do the indexing stuff yourself,



B = np.equal.outer(np.arange(N), M).view(np.int8)

np.array_equal(A, B)
# True





share|improve this answer















Broadcasted comparison is your friend:



B = (M[None, :] == np.arange(N)[:, None, None]).view(np.int8)

np.array_equal(A, B)
# True


The idea is to expand the dimensions in such a way that the comparison can be broadcasted in the manner desired.




As pointed out by @Alex Riley in the comments, you can use np.equal.outer to avoid having to do the indexing stuff yourself,



B = np.equal.outer(np.arange(N), M).view(np.int8)

np.array_equal(A, B)
# True






share|improve this answer














share|improve this answer



share|improve this answer








edited Apr 5 at 22:45

























answered Apr 5 at 22:19









coldspeedcoldspeed

141k25157245




141k25157245







  • 1





    Good answer - just to point out there's a superfluous newaxis in your indexing for M (resulting in a 4D array). You could use M[None, :] instead to get the 3D array. An alternative to avoid fiddly indexing is to use np.equal.outer(np.arange(N), M).view(np.int8).

    – Alex Riley
    Apr 5 at 22:34












  • @AlexRiley Thanks for that! And the outer solution is quite neat.

    – coldspeed
    Apr 5 at 22:45












  • 1





    Good answer - just to point out there's a superfluous newaxis in your indexing for M (resulting in a 4D array). You could use M[None, :] instead to get the 3D array. An alternative to avoid fiddly indexing is to use np.equal.outer(np.arange(N), M).view(np.int8).

    – Alex Riley
    Apr 5 at 22:34












  • @AlexRiley Thanks for that! And the outer solution is quite neat.

    – coldspeed
    Apr 5 at 22:45







1




1





Good answer - just to point out there's a superfluous newaxis in your indexing for M (resulting in a 4D array). You could use M[None, :] instead to get the 3D array. An alternative to avoid fiddly indexing is to use np.equal.outer(np.arange(N), M).view(np.int8).

– Alex Riley
Apr 5 at 22:34






Good answer - just to point out there's a superfluous newaxis in your indexing for M (resulting in a 4D array). You could use M[None, :] instead to get the 3D array. An alternative to avoid fiddly indexing is to use np.equal.outer(np.arange(N), M).view(np.int8).

– Alex Riley
Apr 5 at 22:34














@AlexRiley Thanks for that! And the outer solution is quite neat.

– coldspeed
Apr 5 at 22:45





@AlexRiley Thanks for that! And the outer solution is quite neat.

– coldspeed
Apr 5 at 22:45













6














You can make use of some broadcasting here:



P = np.arange(N)
Y = np.broadcast_to(P[:, None], M.shape)
T = np.equal(M, Y[:, None]).astype(int)



Alternative using indices:



X, Y = np.indices(M.shape)
Z = np.equal(M, X[:, None]).astype(int)





share|improve this answer

























  • This answer was really helpful towards my understanding of broadcasting, thank you!

    – seveibar
    Apr 6 at 0:58















6














You can make use of some broadcasting here:



P = np.arange(N)
Y = np.broadcast_to(P[:, None], M.shape)
T = np.equal(M, Y[:, None]).astype(int)



Alternative using indices:



X, Y = np.indices(M.shape)
Z = np.equal(M, X[:, None]).astype(int)





share|improve this answer

























  • This answer was really helpful towards my understanding of broadcasting, thank you!

    – seveibar
    Apr 6 at 0:58













6












6








6







You can make use of some broadcasting here:



P = np.arange(N)
Y = np.broadcast_to(P[:, None], M.shape)
T = np.equal(M, Y[:, None]).astype(int)



Alternative using indices:



X, Y = np.indices(M.shape)
Z = np.equal(M, X[:, None]).astype(int)





share|improve this answer















You can make use of some broadcasting here:



P = np.arange(N)
Y = np.broadcast_to(P[:, None], M.shape)
T = np.equal(M, Y[:, None]).astype(int)



Alternative using indices:



X, Y = np.indices(M.shape)
Z = np.equal(M, X[:, None]).astype(int)






share|improve this answer














share|improve this answer



share|improve this answer








edited Apr 5 at 22:39

























answered Apr 5 at 22:19









user3483203user3483203

32.1k82857




32.1k82857












  • This answer was really helpful towards my understanding of broadcasting, thank you!

    – seveibar
    Apr 6 at 0:58

















  • This answer was really helpful towards my understanding of broadcasting, thank you!

    – seveibar
    Apr 6 at 0:58
















This answer was really helpful towards my understanding of broadcasting, thank you!

– seveibar
Apr 6 at 0:58





This answer was really helpful towards my understanding of broadcasting, thank you!

– seveibar
Apr 6 at 0:58











3














You can index into the identity matrix like so



 A = np.identity(N, int)[:, M]


or so



 A = np.identity(N, int)[M.T].T


Or use the new (v1.15.0) put_along_axis



A = np.zeros((N,5,5), int)
np.put_along_axis(A, M[None], 1, 0)


Note if N is much larger than 5 then creating an NxN identity matrix may be considered wasteful. We can mitigate this using stride tricks:



def read_only_identity(N, dtype=float):
z = np.zeros(2*N-1, dtype)
s, = z.strides
z[N-1] = 1
return np.lib.stride_tricks.as_strided(z[N-1:], (N, N), (-s, s))





share|improve this answer




















  • 1





    This is great, really interesting answer.

    – user3483203
    Apr 5 at 23:47






  • 1





    Hi Paul, this answer is really elegant, but the identity answers seem specific to the case where the N=M.shape[0]=M.shape[1]. Is the solution similarly elegant for N=/=M.shape[0]=/=M.shape[1]? Thanks for the answer, learning a lot!

    – seveibar
    Apr 6 at 0:55






  • 1





    @seveibar I've updated the answer. It is really just a matter of replacing the correct 5s with Ns.

    – Paul Panzer
    Apr 6 at 1:13















3














You can index into the identity matrix like so



 A = np.identity(N, int)[:, M]


or so



 A = np.identity(N, int)[M.T].T


Or use the new (v1.15.0) put_along_axis



A = np.zeros((N,5,5), int)
np.put_along_axis(A, M[None], 1, 0)


Note if N is much larger than 5 then creating an NxN identity matrix may be considered wasteful. We can mitigate this using stride tricks:



def read_only_identity(N, dtype=float):
z = np.zeros(2*N-1, dtype)
s, = z.strides
z[N-1] = 1
return np.lib.stride_tricks.as_strided(z[N-1:], (N, N), (-s, s))





share|improve this answer




















  • 1





    This is great, really interesting answer.

    – user3483203
    Apr 5 at 23:47






  • 1





    Hi Paul, this answer is really elegant, but the identity answers seem specific to the case where the N=M.shape[0]=M.shape[1]. Is the solution similarly elegant for N=/=M.shape[0]=/=M.shape[1]? Thanks for the answer, learning a lot!

    – seveibar
    Apr 6 at 0:55






  • 1





    @seveibar I've updated the answer. It is really just a matter of replacing the correct 5s with Ns.

    – Paul Panzer
    Apr 6 at 1:13













3












3








3







You can index into the identity matrix like so



 A = np.identity(N, int)[:, M]


or so



 A = np.identity(N, int)[M.T].T


Or use the new (v1.15.0) put_along_axis



A = np.zeros((N,5,5), int)
np.put_along_axis(A, M[None], 1, 0)


Note if N is much larger than 5 then creating an NxN identity matrix may be considered wasteful. We can mitigate this using stride tricks:



def read_only_identity(N, dtype=float):
z = np.zeros(2*N-1, dtype)
s, = z.strides
z[N-1] = 1
return np.lib.stride_tricks.as_strided(z[N-1:], (N, N), (-s, s))





share|improve this answer















You can index into the identity matrix like so



 A = np.identity(N, int)[:, M]


or so



 A = np.identity(N, int)[M.T].T


Or use the new (v1.15.0) put_along_axis



A = np.zeros((N,5,5), int)
np.put_along_axis(A, M[None], 1, 0)


Note if N is much larger than 5 then creating an NxN identity matrix may be considered wasteful. We can mitigate this using stride tricks:



def read_only_identity(N, dtype=float):
z = np.zeros(2*N-1, dtype)
s, = z.strides
z[N-1] = 1
return np.lib.stride_tricks.as_strided(z[N-1:], (N, N), (-s, s))






share|improve this answer














share|improve this answer



share|improve this answer








edited Apr 6 at 1:08

























answered Apr 5 at 23:45









Paul PanzerPaul Panzer

31.8k21845




31.8k21845







  • 1





    This is great, really interesting answer.

    – user3483203
    Apr 5 at 23:47






  • 1





    Hi Paul, this answer is really elegant, but the identity answers seem specific to the case where the N=M.shape[0]=M.shape[1]. Is the solution similarly elegant for N=/=M.shape[0]=/=M.shape[1]? Thanks for the answer, learning a lot!

    – seveibar
    Apr 6 at 0:55






  • 1





    @seveibar I've updated the answer. It is really just a matter of replacing the correct 5s with Ns.

    – Paul Panzer
    Apr 6 at 1:13












  • 1





    This is great, really interesting answer.

    – user3483203
    Apr 5 at 23:47






  • 1





    Hi Paul, this answer is really elegant, but the identity answers seem specific to the case where the N=M.shape[0]=M.shape[1]. Is the solution similarly elegant for N=/=M.shape[0]=/=M.shape[1]? Thanks for the answer, learning a lot!

    – seveibar
    Apr 6 at 0:55






  • 1





    @seveibar I've updated the answer. It is really just a matter of replacing the correct 5s with Ns.

    – Paul Panzer
    Apr 6 at 1:13







1




1





This is great, really interesting answer.

– user3483203
Apr 5 at 23:47





This is great, really interesting answer.

– user3483203
Apr 5 at 23:47




1




1





Hi Paul, this answer is really elegant, but the identity answers seem specific to the case where the N=M.shape[0]=M.shape[1]. Is the solution similarly elegant for N=/=M.shape[0]=/=M.shape[1]? Thanks for the answer, learning a lot!

– seveibar
Apr 6 at 0:55





Hi Paul, this answer is really elegant, but the identity answers seem specific to the case where the N=M.shape[0]=M.shape[1]. Is the solution similarly elegant for N=/=M.shape[0]=/=M.shape[1]? Thanks for the answer, learning a lot!

– seveibar
Apr 6 at 0:55




1




1





@seveibar I've updated the answer. It is really just a matter of replacing the correct 5s with Ns.

– Paul Panzer
Apr 6 at 1:13





@seveibar I've updated the answer. It is really just a matter of replacing the correct 5s with Ns.

– Paul Panzer
Apr 6 at 1:13

















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55543949%2fhow-to-efficiently-unroll-a-matrix-by-value-with-numpy%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

រឿង រ៉ូមេអូ និង ហ្ស៊ុយលីយេ សង្ខេបរឿង តួអង្គ បញ្ជីណែនាំ

QGIS export composer to PDF scale the map [closed] Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Announcing the arrival of Valued Associate #679: Cesar Manara Unicorn Meta Zoo #1: Why another podcast?Print Composer QGIS 2.6, how to export image?QGIS 2.8.1 print composer won't export all OpenCycleMap base layer tilesSave Print/Map QGIS composer view as PNG/PDF using Python (without changing anything in visible layout)?Export QGIS Print Composer PDF with searchable text labelsQGIS Print Composer does not change from landscape to portrait orientation?How can I avoid map size and scale changes in print composer?Fuzzy PDF export in QGIS running on macSierra OSExport the legend into its 100% size using Print ComposerScale-dependent rendering in QGIS PDF output

PDF-ში გადმოწერა სანავიგაციო მენიუproject page