unknown vector size python

Question:

I have a matlab code that I’m trying to translate in python.
I’m new on python but I have been able to answer a lot of questions googling a little bit.
But now, I’m trying to figure out the following:
I have a for loop when I apply different things on each column, but you don’t know the number of columns. For example.
In matlab, nothing easier than this:

    for n = 1:size(x,2); y(n) = mean(x(:,n)); end  

But I have no idea how to do it on python when, for example, the number of columns is 1, because I can’t do x[:,1] in python.
Any idea?

Thanx

Asked By: tete

||

Answers:

Try numpy. It is a python bindings for high-performance math library written in C. I believe it has the same concepts of matrix slice operations, and it is significantly faster than the same code written in pure python (in most cases).

Regarding your example, I think the closest would be something using numpy.mean.

In pure python it is hard to calculate mean of column, but it you are able to transpose the matrix you could do it using something like this:

# there are no builtin avg function
def avg(lst):
    return sum(lst)/len(lst)

rows = list(avg(row) for row in a)
Answered By: J0HN

Yes, if you use numpy you can use x[:,1], and also you get other data structures (vectors instead of lists), the main difference between matlab and numpy is that matlab uses matrices for calculations and numpy uses vectors, but you get used to it, I think this guide will help you out.

Answered By: aehs29

this is one way to do it

from numpy import *
x=matrix([[1,2,3],[2,3,4]])
[mean(x[:,n]) for n in range(shape(x)[1])]

# [1.5, 2.5, 3.5]
Answered By: jack onsl
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.