Looping through piecewise() takes too long, look for code efficiency.

I need to find intersections of a step function and a logistic function for 70,000 times. This is to solve an equilibrium problem with 70,000 groups of data. Basically, I have 15 columns of data as parameters (p1-p6, q1-q6, a, b, midtdemand). Every loop, one row of data will be used to solve for the intersection. I have set up the following code using a for loop:
load tbl85.txt;
% define variables
mktid = tbl85(:,1);
p1 = tbl85(:,2);
q1 = tbl85(:,3);
p2 = tbl85(:,4);
q2 = tbl85(:,5);
p3 = tbl85(:,6);
q3 = tbl85(:,7);
p4 = tbl85(:,8);
q4 = tbl85(:,9);
p5 = tbl85(:,10);
q5 = tbl85(:,11);
p6 = tbl85(:,12);
q6 = tbl85(:,13);
midtdemand = tbl85(:,14);
a = tbl85(:,15);
b = tbl85(:,16);
%price and quantity: store my results
price = size(71239,1);
quantity = size(71239,1);
%The loop to solve for the intersection for 71239 times
for i=1:71239
syms q p
equ1= q == piecewise(p1(i,1)<=p<p2(i,1), q1(i,1), p2(i,1)<=p<p3(i,1), q2(i,1), ...
p3(i,1)<=p<p4(i,1), q3(i,1), p4(i,1)<=p<p5(i,1), q4(i,1), p5(i,1)<=p<p6(i,1), q5(i,1), p6(i,1)<=p, q6(i,1));
equ2= p == piecewise(0<q<q1(i,1), p1(i,1),q1(i,1)<q<q2(i,1), p2(i,1),q2(i,1)<q<q3(i,1),p3(i,1),...
q3(i,1)<q<q4(i,1), p4(i,1),q4(i,1)<q<q5(i,1), p5(i,1),q5(i,1)<q<q6(i,1), p6(i,1));
equ3= p== (log(midtdemand(i,1)/q-1)-a(i,1))/b(i,1);
%solve for intersection on the horizontal steps
[solp,solq]=solve(equ2,equ3);
if size([solp,solq])~=0
price(i,1) = vpa(solp);
quantity(i,1) = vpa(solq);
else
[solp,solq]=solve(equ1,equ3); %solve for intersection on the vertical steps
if size([solp,solq])~=0
price(i,1) = vpa(solp);
quantity(i,1) = vpa(solq);
else
price(i,1)= 99999;
quantity(i,1)= 99999;
end
end
end
end
It turns out my loop takes almost 48 hours to finish... This code is really inefficient...
I have thought about solving it in a matrix form, but I can't figure out how to use matrix in the piecewise(). I have also thought about the if statement, but the logic is pretty complex as the number of steps are not fixed (sometimes, say p3-p6,q3-q6 are all 0). That is why I added the additional vertical piecewise() function to account for the last infinite vertical line in the graph.
Is there any way to improve the computing speed?

1 Comment

"Is there any way to improve the computing speed?"
Probably by doing a numeric calculation, rather than a symbolic one.

Sign in to comment.

Answers (0)

Asked:

on 13 Sep 2018

Commented:

on 13 Sep 2018

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!