-1

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?

pnuts
  • 58,317
  • 11
  • 87
  • 139
Mac
  • 991
  • 3
  • 11
  • 22

1 Answers1

1

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]) ...
vikramls
  • 1,802
  • 1
  • 11
  • 15
  • I did the first part and it really works fine, but the replacing str by words didn't really work. Could you be a little more clear in this part? – Mac Apr 06 '15 at 23:38
  • 1
    I added an update which illustrates the use of the list `words`. Basically you were creating a new string for every `+` that you called on your out_string. Storing the components in a `list` (words) is a common python idiom and used to generate longer strings more efficiently. – vikramls Apr 07 '15 at 00:15
  • It only gives me the error: words =[] ^ IndentationError: expected an indented block – Mac Apr 07 '15 at 00:19
  • 1
    Looks like the copy/paste didn't work for `words`. It needs to be indented correctly below the `for` loop declaration. – vikramls Apr 07 '15 at 00:22