I have the following function handle uppercase K and array of lowercase k and gamma values.
N = 3;
k = randi([1,1000],N+1,1,"double");
gamma = randi([1,100],N+1,1,"double");
K = @(x) [zeros(N,N)];
I need to populate this function handle with specific values of lowercase k and x. For this example with N=3, the corresponding uppercase K matrix is:
Looking at this uppercase K matrix, one can see that the pattern is to start with the first two elements in the matrix in green, copy their values, shift them to the right once, shift them down once, and increase the index of each variable in the elements by 1.
I would like to return uppercase K using the following function:
function K = karray (k,N)
K = @(x) [zeros(N,N)];
for i=1:1:N
for j=1:1:N
K(i,j) = (k(i)*gamma(i)+k(i+1)*gamma(i+1))*x(i)^2+k(i)+k(i+1);
K(i,j+1) = -3*k(i+1)*gamma(i+1)*x(i)^2-k(i+1);
end
end
end
My initial thought was to use a nested for loop to populate uppercase K, but since K is a function handle, I can't simply access each element in K by using K(i,j)
. I think that my method for populating K is correct, but I'm not sure how to properly access each element in K.
EDIT:
How do you remove the N+1
th gamma and k terms from the uppercase K matrix? For example, for N=3
, how do you remove k_4
and gamma_4
to get:
Here spdiags is used to create the diagonal matrix. Otherwise you may use for loops to fill the diagonal matrix.
function K = karray(k, gamma, N)
K = @(x) make_diagonal(x, k, gamma, N);
end
function out = make_diagonal(x, k, gamma, N)
x = x(:);
x = [x(1:N); 0];
ck = circshift(k, -1);
cg = circshift(gamma, -1);
cx = circshift(x, -1);
ccx =circshift(x, 1);
d1 = -3 .* ck .* cg .* cx .^ 2 - ck;
d2 = (k .* gamma + ck .* cg) .* x .^ 2 + k + ck;
d3 = -3 .* k .* ccx .^ 2 - k;
out = full(spdiags([d1 d2 d3], -1:1, N, N));
end
EDIT: In response to the edited question of how do you remove k_4
and gamma_4
?
You need to set ck(end) = 0;
and cg(end) = 0;
before computing d1
, d2
and d3
.