John
John

Reputation: 535

Translate Matlab matrix concatenation to Python

How to translate the following matlab code for matrix concatenation to python?

nr_a = 10;
nc_a = 23;
nr_b = 500;
a = zeros(nr_a, nc_a);
b = zeros(nr_b, nc_a - 1);
c = zeros(nr_b, 1);
d = [ a; b c];

In python, d.shape should equal (nr_a+nr_b, nc_a). My incorrect python solution is

d = np.block([a, [b, c]])

Upvotes: 2

Views: 116

Answers (2)

Adam.Er8
Adam.Er8

Reputation: 13413

np.block requires you to wrapp a in a list as well, like this:

import numpy as np

nr_a = 10
nc_a = 23
nr_b = 500
a = np.zeros((nr_a, nc_a))
b = np.zeros((nr_b, nc_a - 1))
c = np.zeros((nr_b, 1))
d = np.block([[a], [b, c]])

print(d.shape)

Output:

(510, 23)

Internally it just uses concatenate recursively, but saves you the trouble of repeating it yourself (and looks much cleaner for bigger usages).

Upvotes: 2

Jmonsky
Jmonsky

Reputation: 1519

This should do the trick.

import numpy as np

nr_a = 10
nc_a = 23
nr_b = 500
a = np.zeros((nr_a, nc_a))
b = np.zeros((nr_b, nc_a - 1))
c = np.zeros((nr_b, 1))
d = np.concatenate((a, np.concatenate((b, c), axis=1)))

Upvotes: 3

Related Questions