Generating an array of functions
显示 更早的评论
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
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
2020-12-10
Walter Roberson
2020-12-10
This is not pretty, but:
P{w_max + 2 +w*w_max + k -6} = @(x)struct('f', @(y) x(n-w-1)*y(n-k-1));
and the invokation would look like
P{2}(3).f(4)
I dislike this hack of returning a struct that you then immediately pull a field out of. There are usually better ways -- if you are always going to invoke it in this kind of sequence without saving to intermediate arrays, then you are better of creating a single level function of two variables
Bradley Kitzul
2020-12-10
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
类别
在 帮助中心 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!