Create trinomial tree scenarios in matrix rows - matlab

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.

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

Related

Distance between any combination of two points

I have 100 coordinates in a variable x in MATLAB . How can I make sure that distance between all combinations of two points is greater than 1?
You can do this in just one simple line, with the functions all and pdist:
if all(pdist(x)>1)
...
end
Best,
First you'll need to generate a matrix that gives you all possible pairs of coordinates. This post can serve as inspiration:
Generate a matrix containing all combinations of elements taken from n vectors
I'm going to assume that your coordinates are stored such that the columns denote the dimensionality and the rows denote how many points you have. As such, for 2D, you would have a 100 x 2 matrix, and in 3D you would have a 100 x 3 matrix and so on.
Once you generate all possible combinations, you simply compute the distance... which I will assume it to be Euclidean here... of all points and ensure that all of them are greater than 1.
As such:
%// Taken from the linked post
vectors = { 1:100, 1:100 }; %// input data: cell array of vectors
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
%// Index into your coordinates array
source_points = x(combs(:,1), :);
end_points = x(combs(:,2), :);
%// Checks to see if all distances are greater than 1
is_separated = all(sqrt(sum((source_points - end_points).^2, 2)) > 1);
is_separated will contain either 1 if all points are separated by a distance of 1 or greater and 0 otherwise. If we dissect the last line of code, it's a three step procedure:
sum((source_points - end_points).^2, 2) computes the pairwise differences between each component for each pair of points, squares the differences and then sums all of the values together.
sqrt(...(1)...) computes the square root which gives us the Euclidean distance.
all(...(2)... > 1) then checks to see if all of the distances computed in Step #2 were greater than 1 and our result thus follows.

Matlab code for generating a particular class of matrices

I need to generate all square matrices of order n with given properties.
Matrices are symmetric.
Entries are 0 and 1.
Diagonal elements are zeros.
I am using Matlab2012b. Can you help me with the code?
I was trying to write it down. It needs a long sequences of for loops. Any simpler technique?
Try this:
N = 4; %// matrix size
M = (N^2-N)/2; %// number of values to fill in each matrix
P = 2^M; %// number of matrices
x = dec2bin(0:P-1)-'0'; %// each row contains the values of a matrix, "packed" in a vector
result = NaN(N,N,P); %// preallocate
for k = 1:P
result(:,:,k) = squareform(x(k,:)); %// unpack values
end
The matrices are result(:,:,1), result(:,:,2) etc.

Generate All Possible combinations of a Matrix in Matlab

How can I generate ALL possible values for an N*M matrix, knowing that elements of this matrix can only be either be 0 or 1?
For example if I want a 2*2 matrix, we get 16 matrices with the different possible combinations: [0 0;0 0], [1 1;1 1], [1 0;0 1],[1 1; 0 0],[0 0;1 1]...etc
Use dec2base -
combs = dec2base(0:power(2,N*M)-1,2) - '0'
This generates all the possible combinations in rows. So, to select any combination, you need to index into combs. Thus, the first combination [0,0,0,0] would be available at combs(1,:) and the last one [1,1,1,1] would be at comb(end,:).
If your possible values are from a different set, like 0,1,2,3 instead, make this edit -
combs = dec2base(0:power(4,N*M)-1,4) - '0'
If you would to get the combinations that would be sized identically to the input matrix, use this -
combs_matshaped = reshape(permute(combs,[3 2 1]),N,M,[])
This creates a 3D array of as many 2D slices as there are combinations and each combination for the matrix is "index-able" with the third dimension index. For example, if you intend to get the first combination, use combs_matshaped(:,:,1) and for the last one, use combs_matshaped(:,:,end).
Another possibility (although Divakar's answer is simpler and probably faster):
c = cell(1,N*M);
[c{end:-1:1}] = ndgrid([0 1 2 3 ]); %// or change set of values: [0 1 2 3] etc
combs = cell2mat(cellfun(#(x) x(:), c, 'uni', 0)); %// results as row vectors
combs = reshape(combs.',N,M,[]); %// NxM matrices: combs(:,:,1), combs(:,:,2),...

How to find all permutations (with repetition) in MATLAB?

Suppose I have 4 letters and I want to arrange them in 3 places (repetition allowed), so I would have 43=64 possible permutations. How can I compute and print them?
Simplifying Amro's answer, you could use this:
%// Sample data
x = 'ABCD'; %// Set of possible letters
K = 3; %// Length of each permutation
%// Create all possible permutations (with repetition) of letters stored in x
C = cell(K, 1); %// Preallocate a cell array
[C{:}] = ndgrid(x); %// Create K grids of values
y = cellfun(#(x){x(:)}, C); %// Convert grids to column vectors
y = [y{:}]; %// Obtain all permutations
Matrix y should store the permutations you're after.
How about the function N_PERMUTE_K from the File Exchange?
An intuitive one-liner:
unique(nchoosek(repmat('ABCD', 1,4), 3), 'rows')
Although nice-looking, it's slow and inefficient. Don't use it for large data sets.
Pseudocode solution:
Generate the (base ten) numbers 0 to 63.
Change them to base 4, which only has the digits 0, 1, 2, and 3.
Convert numbers to letters.
The actual Matlab code is left as an exercise for the student.

2d matrix histogram in matlab that interprets each column as a separate element

I have a 128 x 100 matrix in matlab, where each column should be treated as a separate element. Lets call this matrix M.
I have another 128 x 2000 matrix(called V) composed of columns from matrix M.
How would I make a histogram that maps the frequency of each column being used in the second matrix?
hist(double(V),double(M)) gives the error:
Error using histc
Edge vector must be monotonically
non-decreasing.
what should I be doing?
Here is an example. We start with data that resembles what you described
%# a matrix of 100 columns
M = rand(128,100);
sz = size(M);
%# a matrix composed of randomly selected columns of M (with replacement)
V = M(:,randi([1 sz(2)],[1 2000]));
Then:
%# map the columns to indices starting at 1
[~,~,idx] = unique([M,V]', 'rows', 'stable');
idx = idx(sz(2)+1:end);
%# count how many times each column occurs
count = histc(idx, 1:sz(2));
%# plot histogram
bar(1:sz(2), count, 'histc')
xlabel('column index'), ylabel('frequency')
set(gca, 'XLim',[1 sz(2)])
[Lia,Locb] = ismember(A,B,'rows') also returns a vector, Locb,
containing the highest index in B for each row in A that is also a row
in B. The output vector, Locb, contains 0 wherever A is not a row of
B.
ismember with the rows argument can identify which row of one matrix the rows of another matrix come from. Since it works on rows, and you are looking for columns, just transpose both matrices.
[~,Locb]=ismember(V',M');
histc(Locb)