0

I am kind of new in Python. I am trying to convert some MATLAB code to Python. This MATLAB code uses a lot of arrays, such as x = [-0.22258 0.50889 -0.35733 -0.22992 -0.26910]. I need to do all kinds of mathematical operations on these arrays, e.g. +/-/* and division. What is the best way to express an array of numbers in Python for this purpose?

Thank you.

1 Answer 1

4

You're looking for numpy:

import numpy as np

x = np.array([-0.22258, 0.50889, -0.35733, -0.22992, -0.26910])

For instance:

x = np.array([-0.22258, 0.50889, -0.35733, -0.22992, -0.26910])
y = np.array([10,9,8,7,6])

>>> x/y
array([-0.022258  ,  0.05654333, -0.04466625, -0.03284571, -0.04485   ])

>>> x+y
array([ 9.77742,  9.50889,  7.64267,  6.77008,  5.7309 ])

>>> x-y
array([-10.22258,  -8.49111,  -8.35733,  -7.22992,  -6.2691 ])

and LOTS of much more complicated numerical computation capabilities. The documentation says it all.

As a side note, since it seems you're a MATLAB user, you can take a look at this NumPy for MATLAB users conversion table, I used it quite a bit to get me started when I was translating an algorithm from MATLAB to Python.

Sign up to request clarification or add additional context in comments.

4 Comments

This doesn't work with Python3.3. Is there a solution for Python3.3?
It's one of the most widely used python packages, and should work for any recent python, including 3.3, it's probably just that you don't have it installed. Try pip install numpy from your command prompt (not in your python interperter), assuming you have pip installed. Here's a link to get your installation running
No matter where I run pip in the command window, I always got "pip is not recognized as an internal or external command, operable program or batch file." However, in Python window, it is confirmed that 'pip' was installed. Any thoughts on this issue?
then you'll need to install pip. In any case, if you want to install basically any package in python, you'll find that pip is the easiest way to go, or, you could use a python distribution from anaconda, which is bundled with many popular packages.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.