3

I am using multidimensional list with numpy

I have a list.

l = [[0 2 8] [0 2 7] [0 2 5] [2 4 5] [ 8 4 7]] 

I need to find square root of sum of square of columns.

0 2 8 0 2 7 0 2 5 2 4 5 8 4 7 

output as,

l = [sqrt((square(0) + square(0) + square(0) + square(2) + square(8)) sqrt((square(2) + square(2) + square(2) + square(4) + square(4)) sqrt((square(8) + square(7) + square(5)) + square(5) + square(7))] 

4 Answers 4

12
>>> import numpy as np >>> a = np.array([[0, 2, 8], [0, 2, 7], [0, 2, 5], [2, 4, 5], [ 8, 4, 7]]) >>> np.sqrt(np.sum(np.square(a), axis=0)) array([ 8.24621125, 6.63324958, 14.56021978]) 
Sign up to request clarification or add additional context in comments.

2 Comments

I think the inner sqrt should be a square
@AshwiniChaudhary : sorry mistaken in writting question. I have updated question.
4

Use the standard function numpy.linalg.norm for this...

import numpy as np a = np.array([[0, 2, 8], [0, 2, 7], [0, 2, 5], [2, 4, 5], [ 8, 4, 7]]) np.linalg.norm(a,axis=0) 

gives:

array([ 8.24621125, 6.63324958, 14.56021978])

Comments

3
>>> import numpy as np >>> np.sum(np.array(l)**2,axis=0)**.5 array([ 10.67707825, 3.46410162, 11.74734012]) 

Comments

-1

What you want to do is use map/reduce

In theory in can be done using nested for loops but could be done in a more functional way...

for l in matrix: sum all elements**2 in return the squar root of the sum 

A one liner:

map(lambda x: sqrt(lambda r, z: r + z**2, x), matrix) 

But to make it more clear, you could rewrite it as such:

def SumOfSquare(lst): return reduce(lambda r, x: r + x**2, lst) def ListOfRoot(lst): return map(lambda x: SumOfSquare(x), lst) s = ListOfRoot(matrix) 

Misread the question, it's without numpy.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.