0

So I have two matrix, W and X.

print(W)
array([ 5.76951515, 19.        ])

print(X)
array([[ 1.,  5.],
       [ 1.,  6.],
       [ 1.,  7.],
       [ 1.,  8.],
       [ 1.,  9.],
       [ 1., 10.],
       [ 1., 11.],
       [ 1., 12.],
       [ 1., 13.],
       [ 1., 14.]])

and I'd like multiply both matrix W and X, varying the value of W[1] for each i iterations, like this.

for i in range(10):
  W[1] = i
  yP_ = W @ X.T
  ecm = np.mean((Y - yP_ ) ** 2)
  plt.plot(W[1], ecm, 'o')
plt.show()

is there any way to avoid that for?

1
  • Why do you want to avoid the for? Performance? Commented May 25, 2020 at 17:50

2 Answers 2

2

Try making W shape (10,2), and keeping the range 0-9 in the second column. Then the rows of the product W @ X.T are the iterations of your current for-loop.

W2 = np.full((10,2), W[0])
W2[:,1] = np.arange(10)
W2
# array([[5.76951515, 0.        ],
#        [5.76951515, 1.        ],
#          ...
#        [5.76951515, 9.        ]])

So you can do

ecm = np.mean((Y - W2 @ X.T)**2, axis=1)  # average across columns
plt.plot(W2[:,1], ecm, 'o')
Sign up to request clarification or add additional context in comments.

Comments

1

You can start by generating the modified W array, and then apply the matrix product just as you where:

N=10
W_ = np.c_[[W[0]]*N, np.arange(N)]
yP_ = [email protected]

Quick check:

yP_ = []
for i in range(N):
    W[1] = i
    yP_.append(W @ X.T)

np.allclose(np.array(yP_), [email protected])
# True

3 Comments

Thanks, it works perfectly. I think your answer is more efficient than the other guy's because he's filling the array and then updates the column, however both of you helped me. If you agree, I will accept his answer, according to SO he replied faster, and he has many fewer points in his account than you have. Also, I think it could motivate him to keep answering questions. Anyway, tell me if that's okay with you.
It's entirely up to you @Sharki But that is maybe overthinking it a little bit :) Generally you should keep in mind what future visitors will benefit of the most, though this question is quite specific, so it doesn't matter as much in this case.
You're right, it just feels a little unfair since both of you helped me so I can't promote both of you, however, thanks! :)

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.