Oria Gruber
Oria Gruber

Reputation: 1533

How to handle concatenate with empty matrix

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

Answers (3)

Abhishek Vijayan
Abhishek Vijayan

Reputation: 753

The best way to do it as follows:

  • Initialize three variables a, b and c corresponding to A, B and C matrices and set them to zero.
  • Now, wherever the assignment of A, B and C is taking place, change the value of the variables a, b and c respectively.
  • After all the assignments, you will get to know which one is None using a,b and c.

Upvotes: 0

Giuseppe Angora
Giuseppe Angora

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

Eric
Eric

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 Nones:

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

Related Questions