So, I want to solve an equation z with two variables (x and y having 50 values each, for example). I want to calculate something like:
import numpy as np
x = np.linspace(0, 50, 51)
y = np.linspace(100, 150, 51)
z=y-x
print z
with open("output_data.csv","w") as out_file:
for i in range(len(x)):
#print i
out_string=""
out_string+=str(x[i])
#out_string+=str(real(ky2)[i])
#print out_string
out_string += "," + str(z[i])
out_string += "\n"
out_file.write(out_string)
However I want to calculate the first x with all the y's the the second x with all; y's again and so on, until I get a set of 50 values of z, each set with 50 values. Then save in a 50 column file.
What my code is doing so fat is calculating only 50 z's for the 1st x and 1st y, 2nd x and 2nd y and so on.
Any ideas?
You need to change your code so you compute z
inside the for
loop:
for i in range(len(x)):
words = []
z = y-x[i]
words.append(str(x[i]))
words.append(", ".join((str(_z) for _z in z)))
outfile.write(": ".join(words))
outfile.write("\n")
With your code, you only compute z
one time (outside the loop) and this does an item-wise difference of y
and x
as you see.
Having said this, you should change your code to not do str += ...
. If you are accumulating strings, use a list instead:
words = []
words.append(str(x[i]) ...