0

How can I write this code faster in MATLAB? Maybe using vectorizations. Basically I do not know how to vectorize with if. In the following, if an element of the array u is 0, then the while loop happens with an update. If the element is non zero then benefit(c,t,w) = B(c,tprime,w)/u(c,tprime,w); and i(c,t,w) = tprime ; happens.

county_size=3 ; time_size = 3; scenario_size = 3; for c=1:county_size for w=1:scenario_size for t=tt:time_size l = u(c,t,w) ; tprime = t ; while (l==0) if tprime > time_size-1 tprime = time_size + 1 ; B(c,time_size + 1,w) = 0 ; u(c,time_size + 1,w) = 1 ; break end l = u(c,tprime+1,w) ; tprime = tprime + 1 ; end benefit(c,t,w) = B(c,tprime,w)/u(c,tprime,w) ; i(c,t,w) = tprime ; end end end 
10
  • Please provide an executable code. Commented May 22, 2019 at 18:48
  • A description of what you're trying to do would also help. Commented May 22, 2019 at 18:51
  • @beaker I do not wish to have 3 for loops. Commented May 22, 2019 at 18:55
  • 1
    Instead of asking about an attempted solution, it will be better if you ask about your actual problem. Commented May 22, 2019 at 19:05
  • 1
    Also, please provide code that can be run as is. That is, define tt and other required variables Commented May 23, 2019 at 7:21

1 Answer 1

1

I will understand this request for vectorization as a more general, how to improve the performance, looking at this part:

 tprime = t ; while (l==0) if tprime > time_size-1 tprime = time_size + 1 ; B(c,time_size + 1,w) = 0 ; u(c,time_size + 1,w) = 1 ; break end l = u(c,tprime+1,w) ; tprime = tprime + 1 ; end 

The only purpose of the while is to find the first nonzero element in u(c,t:end-1,w). There is a function for this purpose, find with the third argument set to first.

Sign up to request clarification or add additional context in comments.

1 Comment

You have the correct aim of what I wish to do. I can do this without the while loop now as you said with find. How can I do this in a vectorizable way without the outside for loop around c and w?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.