Python Forum

Full Version: For Loop Statement enquiry
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,

I am new to python. I am translating matlab code into python. I am stuck when I want to do the for loop statement as shown
in the last paragraph below. Can anyone help on this? Thank you.

nMonth = Fcst.shape[0]
nProduct = Fcst.shape[1]
nScenario = 1000

FlexCostPremium = 0.14

# Generate Demand Scenarios
import numpy as np
Fcst_nScenario =np.kron(np.ones((nScenario,1)),Fcst)
Bias_nScenario =np.kron(np.ones((nScenario,1)),Bias)
Sigma_nScenario =np.kron(np.ones((nScenario,1)),Sigma)

Error = np.zeros((Fcst_nScenario.shape))

for i in range (nProduct):
    for j in range (nMonth*nScenario):
       Error(j,i)=np.random.standard_normal((Bias_nScenario(j,i),Sigma_nScenario(j,i)))
    end
end
Please use Python tags when posting code. It maintains the indentation and generally looks better.

For loops in Python do not have a terminating keyword. From what I see, you only need to do this:

for i in range(nProduct):
    for j in range(nMonth*nScenario):
        Error = np.random.standard_normal((Bias_nScenario(j,i),Sigma_nScenario(j,i)))
The loop doesn't have any way to store or output the data it's calculating. With "Error(j,i)" were you attempting to insert data at that index?
Noted. Will use Python tags in the future.

Yes, I am attempting to insert the data into the index Error(j,i). Can it be done?
That can be done. Python uses square brackets for slicing and indexing:

for i in range(nProduct):
    for j in range(nMonth*nScenario):
        Error[j,i] = np.random.standard_normal((Bias_nScenario(j,i),Sigma_nScenario(j,i)))
I have tried the above but it has generated the error as below:

TypeError: 'numpy.ndarray' object is not callable
In you use brackets[] to index arrays/matrices, not parentheses().
I have tried using brackets as shown below. However, I still received the error below.
TypeError: 'numpy.ndarray' object is not callable

for i in range(nProduct):
    for j in range(nMonth*nScenario):
        Error[j,i] = np.random.standard_normal((Bias_nScenario(j,i),Sigma_nScenario(j,i)))
Ah, I see it now. It's the _nScenario objects; they're being sliced in the same manner:

for i in range(nProduct):
    for j in range(nMonth*nScenario):
        Error[j,i] = np.random.standard_normal((Bias_nScenario[j,i],Sigma_nScenario[j,i]))
Already tried the above suggested codes but the error below is generated:
TypeError: 'numpy.float64' object cannot be interpreted as an integer