Andrew Raleigh - 3 years ago 170

Python Question

Say I have two matrices, A and B.

I want to calculate the magnitude of difference between the two matrices. That is, without using iteration.

Here's what I have so far:

`def mymagn(A, B):`

i = 0

j = 0

x = np.shape(A)

y = np.shape(B)

while i < x[1]:

while j < y[1]:

np.sum((A[i][j] - B[i][j]) * (A[i][j] - B[i][j]))

j += 1

i += 1

As I understand it, generally the value should be small with two similar matrices but I'm not getting that, can anyone help? Is there any way to get rid of the need to iterate?

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

This should do it:

```
def mymagn(A, B):
return np.sum((B - A) ** 2)
```

For arrays/matrices of the same size, addition/subtraction are element-wise (like in MATLAB). Exponentiation with scalar exponent is also element-wise. And `np.sum`

will by default sum all elements (along all axes).

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**