shripati007 shripati007 - 2 months ago 8
Python Question

How to add corresponding elements of 2 multidimensional matrices in python?

I have 2 multidimensional arrays , both of size 128X640X5. 5 is the number of channels for the matrices. I wish to add the respective channel values of both the matrices for every point in the matrices. For eg if we have A and B as 2 matrices, I wish to do an operation something like this:
A(x,y,0)+B(x,y,0) =A(x,y,0). This should add the 0th channel values of points x and y in both A and B and then store it back in A. Similiary I wish to do it for other 4 channels also. Any idea on how to do this in python? I am using numpy array of python and basically working on image manipulation problem.


In order to add each corresponding point of a ndarray in numpy you can use numpy's add function (numpy.add).

It will add up each corresponding point of two ndarrays which have the same shape. If the arrays do not have the same shape, it will broadcast (change their shape) so that they can be added together.

In your case, you would simply write:

import numpy as np
C = np.add(A, B)