Python Forum
For Loop Statement enquiry
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
For Loop Statement enquiry
#1
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
Reply
#2
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?
Reply
#3
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?
Reply
#4
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)))
Reply
#5
I have tried the above but it has generated the error as below:

TypeError: 'numpy.ndarray' object is not callable
Reply
#6
In you use brackets[] to index arrays/matrices, not parentheses().
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#7
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)))
Reply
#8
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]))
Reply
#9
Already tried the above suggested codes but the error below is generated:
TypeError: 'numpy.float64' object cannot be interpreted as an integer
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020