问题
proc iml;
start tr(x,y); * create function called tr;
N = nrow(x);
dx = x[2:N] - x[1:N-1];
ymean = (y[2:N] + y[1:N-1]) / 2;
return(dx` * ymean );
finish tr;
x = do(-2,5,0.01);
print "Integral of a over x is" ( tr(x,0#x+1) ); *Answer is 7;
I keep receiving the (execution) invalid subscript or subscript out of range. How do I solve this problem and get the correct answer? I've tried taking out the -1 in x[1:N-1]; and y[1:N-1], but it gives me the wrong answer. Is it because I need to assume equally spaced intervals? If so, how would I do that. Trapezoidal equation: (x-x0)*(y+y0)/2 or (xi - xi-1) * (yi + yi-1) / 2.
回答1:
The subscript problem arises from the fact that x
is being treated as a row vector rather than a column vector, so nrow(x) = 1
. That means you've defined n = 1
, so when the index is n-1
, it's actually at 0. That causes a subscript error since SAS IML vectors are indexed from 1 rather than 0. To fix it, use n = ncol(x)
.
Also, as an aside, you can shorten your module tr
if you wanted:
proc iml;
start tr(x, y);
i = 2:ncol(x);
return( (x[i] - x[i-1])` * (y[i] + y[i-1]) / 2 );
finish tr;
x = do(-2, 5, 0.01);
print 'The integral of a over x is' (tr(x, 0#x+1)) 'and should be 7.';
quit;
来源:https://stackoverflow.com/questions/23557047/proc-iml-trapezoidal-rule