Home > front end >  Create a matrix of element (lines) points connectivity python
Create a matrix of element (lines) points connectivity python

Time:10-09

I am new to programming in Python, I would like to create a matrix In matlab, I got to do the following:

    clc;
    nelments= 3   
    npoint= 5
    connect=(1:npoint)   (npoint-1)*(0:nelments-1).'

However, in python I do not know how to create such matrix ?? I tried the following:

import numpy as np 
nelments=3
npoint=5
connect=list(range(1,npoint 1)) (npoint-1)*(list(range(0,nelments))

I hope anyone could help

CodePudding user response:

I see - to do this systematically for m rows and n columns, assuming you start at 1 and want to repeat the last column of each row,

import numpy as np

m=3
n=5
connect = np.array([np.arange(i*(n-1) 1,i*(n-1) n 1) for i in range(m)])

CodePudding user response:

Here's something that very closely matches MATLAB's syntax, and takes advantage of numpy's broadcasting and vectorization features:

def make_fancy_matrix(rows, cols):
    return np.arange(1, cols   1)   (cols - 1)*np.arange(rows)[:, None]

Usage:

>>> make_fancy_matrix(3, 5)
array([[ 1,  2,  3,  4,  5],
       [ 5,  6,  7,  8,  9],
       [ 9, 10, 11, 12, 13]])

>>> make_fancy_matrix(5, 3)
array([[ 1,  2,  3],
       [ 3,  4,  5],
       [ 5,  6,  7],
       [ 7,  8,  9],
       [ 9, 10, 11]])

Here's a simple timing benchmark versus the other answer using a list comprehension:

In [2]: np.array_equal(make_fancy_matrix(10000, 50), comprehension(10000, 50))
Out[2]: True

In [3]: %timeit comprehension(10000, 50)
10.9 ms ± 158 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

In [4]: %timeit make_fancy_matrix(10000, 50)
746 µs ± 10.1 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
  • Related