0

I am trying to generate 100 random column stochastic matrices using a for loop and save them.

Below code is to generate an individual random column stochastic matrix.

import numpy as np
import random

For x in range(100):
    a = 2
    sto = np.identity(2)
    sto = sto + np.random.uniform(low=0.2, high=0.5, size=(a, a))
    sto = sto / sto.sum(axis=0, keepdims=1)
    print(sto)

When I try to implement the operation to generate 100 matrices with a for loop I fail - all matrices generated turn out to be the same.

Edit: I can now generate different matrices in the loop.

But I still don't know how to save them all to use in later work (for instance: saving them to multiply some of them at a later step)?

4
  • I don't see any for loop in your code. Could you show it? Commented Jun 30, 2019 at 0:49
  • Sorry, I just edited it. I think I solved the problem with generating the same matrix over and over again: the ones generated now are different from each other. But I still have the problem with saving them. Commented Jun 30, 2019 at 0:57
  • Append them to a list. Commented Jun 30, 2019 at 1:16
  • I tried that. I basically fail, I generate distinct lists. Commented Jun 30, 2019 at 1:30

3 Answers 3

1

I'm not sure if this is what you are looking for, but basically i created a list named sto1 so that you can access it in the later parts of your code

import numpy as np
import random

sto1 = []
for x in range(100):
    a = 2
    sto = np.identity(2)
    sto = sto + np.random.uniform(low=0.2, high=0.5, size=(a, a))
    sto = sto / sto.sum(axis=0, keepdims=1)
    sto1.append(sto)
print(sto1)
Sign up to request clarification or add additional context in comments.

Comments

0

I am not sure exactly what you expect as the outcome, but I don't think you need a for-loop.

Here is my solution:

a = 2
i = np.expand_dims(np.eye(a), 0)
x = np.random.uniform(low=0.2, high=0.5, size=(100, a, a))
s = i + x
out = s / np.expand_dims(s.sum(1), 1)

In fact, internally a 100-loop adds all values in matching dimensions of i and x. The trick is that expand_dims method creates a dummy dimension to be able to only have one mismatched dimension equal to 1. Then, these operations between two arrays are possible. The second expand_dims also has a similar role but on a different dimension. In the end, if you want it as a list, you can convert it to a list of 100 arrays:

out = list(out)

Comments

0

Why not just save them on the hard-drive:

import numpy as np

random_matrices = np.random.rand(100,2,2)

np.save('random_matrices.npy', random_matrices)

random_matrices_loaded = np.load('random_matrices.npy')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.