1

I have a simple text file composed of 8 columns and I read it with loadtxt function. I want to plot as y-axis column2-column5 and as x-axis column1-column4 divided by cos(column2-column5) so I put this commands

>>> y = data[:,2] - data[:,5]
>>> x = (data[:,1] - data[:,4])/cos(y)
and it gave this error

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'cos' is not defined

What is the problem?

2 Answers 2

3

You probably want to use numpy arrays. Then you can use element wise division. Additionally numpy provides all necessary math functions.

import numpy as np
d = np.asarray(data)
y = d[:,2] - d[:,5]
x = (d[:,1] - d[:,4])/np.cos(y)
Sign up to request clarification or add additional context in comments.

3 Comments

Correct but since they are using loadtxt and 2D indexing I'm sure the variables already are numpy arrays.
Since it was not clear which loadtxt function he is using, np.asarray makes sure that we will have ndarrays. If it is already one, nothing happens.
It is tagged matplotlib so it's surely numpy loadtxt in question. What else can you index like data[:,2]? (not a rhetorical question)
0

cos is in math module (as well as other mathematical libraries like numpy etc.)

import math
math.cos(3) 

for numpy

import numpy
numpy.cos( np.array( [ [1,2], [3,4] ] ) )

1 Comment

-1 the argument is obviously an array, not a scalar, so math.cos won't work for their use case

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.