Calcite | Level 5

## Simple do loop problem

Hi,

I'm a new struggler with IML, and have a noobish question.

What I have here, or would have, is an inner function that for each "timevalue" x makes constant vector c=x, a running time vector t from moment x till the end of data t(x:m), deducts this t from constant x and multiplies with "price" vector p from moment x onwards (e=p[x:m]). Finally s(x) is sum of these rows.

Simple thing expained in complex way but simply but I would like to construct g(x)=SUM operator from x to m [(x-t(x))*p(x)]. Inner function is valid and for example x=3 creates:

t  c  e  d  s

3 3 2 0 -104

4 3 4 -4

5 3 7 -14

6 3 2 -6

7 3 4 -16

8 3 8 -40

9 3 4 -24

But how can I insert x there one by one from 1 to m and get a result vector of s(x:m)?

p={5,6,2,4,7,2,4,8,4};

m=nrow(p);

Start uber(p,m);

w=0;

do i=1 to nrow(p);

x=w+i;

q=(x:m);                    /*m is sample size, a constant from outside of this loop*/

t=q`;                        /*just transposing to get column vector into row vector*/

c=j(nrow(t),1,x);            /*creates row vector of constant x*/

e=p[x:m];

d=(c-t)#e;                /*distance times price*/

s=sum(d);

end;

return (s);         /*given series of prices p, inserting x into this loop gives s(x)=cumulative sum of weight times price for (x:T), OR SHOULD DO SO*/

finish;

1 ACCEPTED SOLUTION

Accepted Solutions
SAS Super FREQ

## Re: Simple do loop problem

I'm not 100% sure that I follow your example, but it sounds like you want ti compute the sum s for each value of x in the loop. To do that, just create s as a vector outside of the loop and assign to s inside the loop:

s = j(m,1);

do i = 1 to nrow(p);

...

s = sum(d);

end;

return( s);

I'll mention that you can accomplish the same computation with many fewer variables. You don't need x (which equals i) and you don't need w, q, e, or c.  Here's a simpler implementation:

s = j(m,1);

do i=1 to nrow(p);

t=T(i:m);          /*m is sample size, a constant */

d=(i-t)#p;      /*distance times price*/

s=sum(d);

end;

2 REPLIES 2
SAS Super FREQ

## Re: Simple do loop problem

I'm not 100% sure that I follow your example, but it sounds like you want ti compute the sum s for each value of x in the loop. To do that, just create s as a vector outside of the loop and assign to s inside the loop:

s = j(m,1);

do i = 1 to nrow(p);

...

s = sum(d);

end;

return( s);

I'll mention that you can accomplish the same computation with many fewer variables. You don't need x (which equals i) and you don't need w, q, e, or c.  Here's a simpler implementation:

s = j(m,1);

do i=1 to nrow(p);

t=T(i:m);          /*m is sample size, a constant */

d=(i-t)#p;      /*distance times price*/

s=sum(d);

end;

Calcite | Level 5

## Re: Simple do loop problem

That indeed does the trick, and also enlightens how to use a loop, thanks!

From The DO Loop