Generating an array of functions

조회 수: 13 (최근 30일)
Bradley Kitzul
Bradley Kitzul 2020년 12월 10일
댓글: Walter Roberson 2020년 12월 10일
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