For loop that references two different arrays

Hello,
I am attempting to create an array “xminxhat” which references the values of two other arrays “xhat” and “yhat”. Essentially, I can’t figure out how to create a for loop that references two different arrays. I’ve shown my code below.

Thanks!
Nakul

x = collect(0:99) #independent variable, sampled 100 times
y = rand(100)*100 #dependent variable, sampled 100 times
xhat = sum(x)/length(x)
yhat = sum(y)/length(y)
xminxhat = []

for a in xhat, b in xminxhat  
    xminxhat[a] = x[a] - xhat[a]
end

You are looking for the the zip function, but I think that your code has some other issues as well. First, xhat is a scalar value, so it doesn’t make sense to index into it as xhat[a], and second, xminxhat is a zero element vector, so you can’t index into that either!

I suspect that this is what you were going for, but my statistics are too rusty to be sure:

x = collect(0:99)
xhat = sum(x)/length(x)
xminxhat = []

for i in x  
    push!(xminxhat, i - xhat)
end
2 Likes

Ah, I totally forgot that xhat is a scalar. push! really comes to the rescue for indexing into zero element vectors.

The code works great, thank you!

You don’t really need push! here, it’s quite slow, and you already know the final vector length. These three lines do the same but are more concise and about 4X faster.

x = 0:99
xhat = mean(x)
xminxhat = collect(x .- xhat)
1 Like

Do you even need to collect the last vector? This is more than 3x faster again:

x = 0:99
xhat = mean(x)
xminxhat = x .- xhat
1 Like

Sure, it is, I just assumed that the OP needed to see the results at that moment, a range will not be very useful for this.

1 Like

OK, but people seem to always be collecting things needlessly, so I think it makes sense to question that impulse.

2 Likes