1

I am trying to convert the following Matlab code to Python:

  n = 10 ;
  T = cell(1, n) ;
  for k = 1 : n
    T{1,k} = 20*k + rand(10) ;
  end

It stored all the matrices generated from the for loop. How can I write a similar code in Python?

1
  • Can you please add an example of the expected output? Commented Oct 4, 2021 at 11:52

1 Answer 1

3

You can use a normal list:

import numpy as np
n = 10
t = []
for k in range(n):
  t.append(20 * (k+1) + np.random.rand(n,n))
print(t)
Sign up to request clarification or add additional context in comments.

6 Comments

I like that you kept the two-space indenting style of the question code :-)
This is correct, but an uncommon mix of python and numpy. Might be what OP is looking for.
Thank @Mohammad. It works well. Now, how to see each of the Matrices separately in an array? For example, in Matlab, after running the Matlab code that I have mentioned in my question, I run the following T1=T{1,1} to see the 1st Matrix and T2=T{1,2} and so on. How can I do that in python? Thank you again.
I got it@Mohammad. I just need to do the following in python: t1=t[1] to see the first array, t2=t[2] to see the second array and so on.
@MMKarim be careful as indexing in python starts at 0, so the first element should be t[0] and not t[1]. If you want to have them all in one array you can use tall =np.ravel(t).reshape(10,-1)
|

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.