Home > Software design >  Acessing element of an array which is a element in a matrix
Acessing element of an array which is a element in a matrix

Time:11-12

Currently I am working on a project where I have to transform a Matlab code into a Python code. Now I am stuck on small problem which might be a big problem.

For example I have a Matrix and I want to give the positions [0][i] the value lets say 1 and i is 0 to 5. The Matrix is 4x4 (to small for [0][5]) but on position [0][0] is an array with 3 elements.

So it would look like codeM = [[array, 1 , 2, 3], [array, 1 , 2, 3], [array, 1 , 2, 3]]code and array would just becode array =[1,2,3]. code

I hope I descripted it clear. Feel free to ask more :D

Now the problem which I have is that I want the first element of the array is [0][0] so that the number 3 in the first row ist [0][5]. Is it possible to declare the first element of an array to the matrix position [0][0]? I am grateful for every solutions or ideas. Thanks :)

CodePudding user response:

Maybe is better solution to use iterable unpacking operator(*) to unpack your iterables

Unpacking in Python refers to an operation that consists of assigning an iterable of values to a tuple (or list ) of variables in a single assignment statement.

Example:

array =[1,2,3]
M = [[*array, 1 , 2, 3], [*array, 1 , 2, 3], [*array, 1 , 2, 3]]
print (M) # [[1, 2, 3, 1, 2, 3], [1, 2, 3, 1, 2, 3], [1, 2, 3, 1, 2, 3]]
print (M[0][5]) # 3

Or add value at beginning of list, there are several solutions, here is one of the examples:

array =[1,2,3]
M = [[array, 1 , 2, 3], [array, 1 , 2, 3], [array, 1 , 2, 3]]
M = [[0,0] l for l in M]
print (M) # [[0, 0, [1, 2, 3], 1, 2, 3], [0, 0, [1, 2, 3], 1, 2, 3], [0, 0, [1, 2, 3], 1, 2, 3]]
print (M[0][5]) # 3

Also you can use Python insert() function:

The insert() method inserts an element to the list at the specified index.

Syntax: list.insert(idx, elem)

for l in M:
    l.insert(0,0)
    l.insert(1,0)
print (M) # [[0, 0, [1, 2, 3], 1, 2, 3], [0, 0, [1, 2, 3], 1, 2, 3], [0, 0, [1, 2, 3], 1, 2, 3]]
print (M[0][5]) # 3
  • Related