Generating an array of functions

6 次查看(过去 30 天)
Hi, I am trying to make a code that will generate candidate terms. These candidate terms will be evaluated later with given x(n)-->input and y(n)-->output. However, in the seccond for loop (xy loop) I am unable to change two of the variables... I can only change the w and not the k. Essentially what I need out of this code is an array with all 36 candidate terms whcih I can call upon in my main code.
% sample eqn: y = 1 + 0.7x(n) + 0.8x(n-1) + 0.3x(n-2)y(n-1)
% this eqn has 36 candidate terms
% --> x(n-w) where w = 0,1,2,3,4,5 --> 6 terms
% __> x(n-w)y(n-k) w = 0,1,2,3,4,5 ... K = 1, 2, 3, 4, 5 -->30 terms
%initializing
K_max = 5;
w_max = 5;
%code for all the x-candidate terms (will produce 6 terms)
for w=1:w_max+1
P{w} = @(w) x(n-w-1);
end
%code for al the xy-candidate terms (will produce 30 terms)
for w=1:w_max+1
for k=1:K_max
P{w_max + 2 +w*w_max + k -6} = @(w)@(k) x(n-w-1)*y(n-k-1); %the left side of this equation just maps it to the 1D array
end
end

回答(1 个)

Walter Roberson
Walter Roberson 2020-12-10
for k=1:K_max
^
P{w_max + 2 +w*w_max + k -6} = @(w)@(k) x(n-w-1)*y(n-k-1); %the left side of this equation just maps it to the 1D array
^^^^
The @(k) shadows the for k . If you need to use the k from the loop, use a different parameter name instead of @(k) . For example,
P{w_max + 2 +w*w_max + k -6} = @(w)@(kk) x(n-w-1)*y(n-k-1); %the left side of this equation just maps it to the 1D array
However, if the k you want is from the for k loop, then it is not clear to me what parameter it is you want for the inner function.
My guess at what you want is:
P{w_max + 2 +w*w_max + k -6} = @(w)x(n-w-1)*y(n-k-1); %the left side of this equation just maps it to the 1D array
  4 个评论
Bradley Kitzul
Bradley Kitzul 2020-12-10
Hi,
Thank you!
I think this will work. Furthermore, if you do not suggest doing this way. Does matlab have any other way where I could store all the candidate terms in an array-- and also access them?
Walter Roberson
Walter Roberson 2020-12-10
You can use 2D cell arrays if you need to, or make functions of two variables.
The kind of arrangement you are using would only be used if you needed one level to generate a new function that you recorded and used multiple times

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by