help-octave
[Top][All Lists]

Re: "Looking back" within a singe vector

 From: Jaroslav Hajek Subject: Re: "Looking back" within a singe vector Date: Sun, 15 Mar 2009 10:18:59 +0100

```On Sun, Mar 15, 2009 at 9:19 AM, Jaroslav Hajek <address@hidden> wrote:
> On Sat, Mar 14, 2009 at 6:19 PM, babelproofreader
>>
>> I have a single vertical vector containing several thousand entries and what
>> I would like to do is loop through the vector and calculate various "moving"
>> calculations, e.g. at v(100,1) I would like to calculate a value for v(80,1)
>> to v(100,1) inclusive, the calculations typically being averages, standard
>> deviations, maximums and minimums and Fisher transformations. Once done,
>> move forward and repeat for v(101,1) etc. A further complication arises in
>> that the length of the look back period varies according to data contained
>> in a second vector. Can anyone suggest what functions I should be looking at
>> to complete such a task?
>
>
> Unless you can and want to reuse parts of the computations as the
> slice progresses, you can do:
> v = ... your data...
> ilb = ... look back indices ....
>
> slice = cell (1, length (v));
> for i = 1:n
>  slice{i} = v(ilb(i):i);
> endfor
>
> and now use cellfun to apply whatever reductions you want to the
> slices, e.g. sum, mean, max...
> It would be nice if the loop could be vectorized, but I don't see a
> way unless we write a new compiled function. It can be done with
> cellfun and an anonymous function, but I don't think it will be
> faster.

Update: realizing that it's a nice generalization of mat2cell (with a
vector) and I may have uses for it myself, I created a "cellslices"
function that can replace a loop of the form
for i = 1:n
s{i} = x(lb(i):ub(i));
endfor

So you can write your example like this:
ilb = ... look back indices ....

# create slices
slices = cellslices (v, ilb, 1:length (v));

# get sums (this would be faster using cumsum, though possibly less accurate)
sums = cellfun (@sum, slices);
# get maxs (this can't be done with cummax, though)
maxs = cellfun (@max, slices);
# get mins, or whatever else you wish...

enjoy!

--
RNDr. Jaroslav Hajek
computing expert & GNU Octave developer
Aeronautical Research and Test Institute (VZLU)
Prague, Czech Republic
url: www.highegg.matfyz.cz

```