Reputation: 1533
I have three matrices A,B,C
, they all have the same amount of rows.
I want to create a new matrix D that is the concatenation of A,B,C with respect to columns.
This is my very simple code
A = numpy.concatenate((A, numpy.concatenate((B, C), axis=1))), axis=1)
When all the matrices exist, it's fine and works as expected.
But sometimes its possible that I will only have A, or only B C etc. Sometimes one or two may be empty. In these cases, the program will fail.
What's the best and most code efficient way to handle this? if B for example does not exist, we will have that B = None
Upvotes: 0
Views: 816
Reputation: 753
The best way to do it as follows:
Upvotes: 0
Reputation: 853
maybe there is a more elegant version but you can use sequence of "if":
if not A is None and not B is None and not C is None:
X = numpy.concatenate((A, numpy.concatenate((B, C), axis=1)), axis=1)
elif A is None:
if not B is None and not C is None:
X = numpy.concatenate((B, C), axis=1)
elif B is None:
X = C
else:
X = B
elif B is None:
if not A is None and not C is None:
X = numpy.concatenate((A, C), axis=1)
elif A is None:
X = C
else:
X = A
elif C is None:
if not A is None and not B is None:
X = numpy.concatenate((A, B), axis=1)
elif A is None:
X = B
else:
X = A
else:
X = None
I hope i help you, good work
Upvotes: 0
Reputation: 97641
Firstly, you can combine your two calls to concatenate
:
result = numpy.concatenate((A, B, C), axis=1)
Two options then - either filter out the None
s:
arrs = [a for a in (A, B, C) if a is not None]
result = numpy.concatenate(arrs, axis=1)
Or better yet, actually use "empty" arrays, rather than passing None
:
A = np.random.randn(3, 5) # your actual data
B = np.zeros((3, 0)) # set to something with the same height as A, not None
C = np.zeros((3, 0)) # still 3 rows, but each row is empty
result = numpy.concatenate((A, B, C), axis=1)
Upvotes: 2