0

In Matlab I'm trying to create a 3^(n-1) by n matrix containing in each row a scenario of a trinomial tree. i.e. in total all the rows together contain all possible paths that can be followed in the tree. At each point in the tree the path goes either up, stay the same or go down. I want to denote this in the matrix with 1, 0 or -1 respectively. An example for n = 3 would be:

[0,-1,-1; 
0,-1,0; 
0,-1,1; 
0,0,-1; 
0,0,0;
0,0,1;
0,1,-1;
0,1,0;
0,1,1]

I want to generalize this for n steps.

dumei
  • 47
  • 5
  • Since there's no actual code provided, this is more a topic for [ComptScienceSE](https://scicomp.stackexchange.com/) – PTRK Apr 27 '20 at 16:01

1 Answers1

0

Your question is basically answered here, written by Luis Mendo. Only minor adjustments required.

What you want are all combinations of:

vectors = { [0], [-1 0 1], [-1 0 1] }; %matching your example

Or more generally for arbitrary:

vectors = [0,repmat({[-1 0 1]},1,n-1)]; %start with 0, then repeat [-1,0,1] n times

Then you can continue with the linked answer, quoting here:

n = numel(vectors); %// number of vectors
combs = cell(1,n); %// pre-define to generate comma-separated list
[combs{end:-1:1}] = ndgrid(vectors{end:-1:1}); %// the reverse order in these two
%// comma-separated lists is needed to produce the rows of the result matrix in
%// lexicographical order 
combs = cat(n+1, combs{:}); %// concat the n n-dim arrays along dimension n+1
combs = reshape(combs,[],n); %// reshape to obtain desired matrix
Daniel
  • 36,610
  • 3
  • 36
  • 69