Generation of a basis vector following a constraint.

2 visualizzazioni (ultimi 30 giorni)
Problem: I Want to generate a set of basis vectors which follows the constraint . While I can do that as seen from the below working example, my code seems tiresome and non-general. Even though the problems seems from Physics, I belief it can be understood without it's knowledge as well.
For N= 2
N = 2;
L = 2;
i = 1;
for n_1 = N:-1:0
for n_2 = N-n_1:-1:0
if n_1 + n_2 == N
basis(i,N-1) = n_1;
basis(i,N) = n_2;
i = i+1;
end
end
end
OUTPUT:
Similarly I can do this for N = 3 which gives a 10 by 3 matrix
M = 3;
L = 3;
j = 1;
for n_1 = M:-1:0
for n_2 = M-n_1:-1:0
for n_3 = M-n_1-n_2:-1:0
if n_1 + n_2 +n_3 == M
basis2(j,M-2) = n_1;
basis2(j,M-1) = n_2;
basis2(j,M) = n_3;
j=j+1;
end
end
end
end
OUTPUT:
I want to write the code which is more general so that, I do not have to rewrite the code everytime if I want a different value for N. Any help regarding the same would be helpful.
Thank You.

Risposta accettata

David Goodmanson
David Goodmanson il 1 Mag 2021
Modificato: David Goodmanson il 1 Mag 2021
Hi Vira,
The for loops that you did are a good approach, but like you say this will become impractical as the length of the vector gets larger. General solution, for the second example:
n = 3; % length of the vector
t = 3; % sum of values
a = nchoosek(1:t+n-1,n-1)
s = size(a,1)
b = [zeros(s,1) a (t+n)*ones(s,1)]
v = diff(b,[],2)-1
Comment: In the second example, you are looking for a vector with 3 values, each value >=0, and the values sum to 3. Suppose the problem is altered temporarily by adding 1 to each value. So now each value is >=1, and the values sum to 6.
Consider a vector of 7 elements, values 0 through 6. Divide the vector into three sections, using two nonidentical movable 'marker' elements that do not include the end points. Here the moveable markers are two elements out of the set of values 1 through 5, and the function nchoosek(1:5,2) give a list of all possible choices. An example is
0 1 2 3 4 5 6
| | | |
m m
Two stationary lines have been added at the end points. Now as the m's move around, the distances between the marker lines are the 3 values you need. These distances have minimum value 1 and add to 6. Subtracting 1 from all three distances gets back to the original problem.
  1 Commento
Vira Roy
Vira Roy il 2 Mag 2021
Thank for the solution David. Not only is it general, it is extremely fast as well for larger values.

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Linear Algebra in Help Center e File Exchange

Prodotti


Release

R2021a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by