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:
x
here?K
being a handle, it is that you’re trying to do everything in an anonymous function. You can create a regular named function, and get the handle to that. In a named function you can use loops and anything else you might need.j
overwrites a result from the previous iteration. That cannot be right.karrray
is a named function. But inside you create an anonymous functionK
to return. Instead return the handle to a named function, as in the answer below.