Question about concatenation using for loops

I am new to coding in general. I know this is probably a simple question, but I’ve been looking through documentation for about an hour.

I have an array of eigenvalues, and I want to return a list of the real eigenvalues that fall between -1 and 1. In Python, I use a for loop and two if statements and the numpy function append to append the values to the end of an empty vector.

 xvals = []
  for eval in evals:
    if(np.abs(np.imag(eval)) < 1e-6):
      xval = np.real(eval)
      if(-1 <= xval and xval <= 1):

I’m translating this into Julia and I’m having a tough time. Here is my code so far:

e= length(evals)
xvals = []
for k=1:e
    if imag(evals[k]) < 1e-6 && imag(evals[k]) > -1e-6
        xval = real(evals[k])
        if xval <= 1 && xval >= -1
            xvals = hcat(xvals, xval)

Specifically, I’m getting a dimensions mismatch error “mismatch in dimension 1, expected 0 got 1”.

I’m also noticing if I try to concatenate an array in a for loop, that the for loop doesn’t seem to recognize global variables. For example the code:

A = [0,]
for i in 1:10
    A = hcat(A,i)

results in an error: a not defined in expression (starting at for loop).

So what is going on here? And, what is the preferred method to create such a vector?


First, the function you want is push!, not hcat: push! is the function to append a single element to an array, whereas hcat is for concatenating matrices horizontally (by columns).

Second, you can accomplish what you are trying much more simply with:

xvals = [real(e) for e in evals if abs(imag(e)) < 1e-6 && -1 <= real(e) <= 1]

Third, you are hitting the infamous global scope rule: when writing to a global variable A in a loop, you need to declare it as global A:

A = [0,]
for i in 1:10
    global A = push!(A,i)

This is not needed in the REPL in Julia 1.5 (or in Jupyter in any version), and in scripts there is a clearer error message, so I’m guessing you are using a very old version of Julia? (If you are writing code inside functions rather than using globals in scripts, which is what you would do for most “serious” code, there is no need for any special declaration.)


thank you for the help!

I’m using Julia 1.4.1.