Can I create several similar anonymous functions with loop and array

I want to create several similar anonymous functions, which depends on elements of an array.
An array is given as an input. Both the length of array and the elements of array are unknown before running the code. For example,
a=[1,2,3]
I want to create anonymous functions ( actually what i want is some other functions defined based on the input array a, but here for simplicity I use polynomial as an example)
f1=1,f2=x, f3=x^2,f4=x^3
and then apply them to other inputs with other calculations. Since I am new to Matlab, the only way I can think of is using a for-loop
temp=cell(1,size(a,2));
temp{1,1}=1;
for i=2:size(a,2)
temp{1,i}=@(x) x.^a(i);
end
But after running the code, I found a(i) actually doesn't become a value when the code is run. And the anonymous functions are hard-coded as x^a(i) during the loop, which is not what I want.
So given an array with arbitrary length or a matrix with arbitrary size, how can I dynamically create several similar anonymous functions depending on the entries of the array?
I hope I express my question clear enough. Thank you.

 Accepted Answer

John - your functions will evaluate correctly even though you see each anonymous function as
@(x)x^a(i)
so there is no need to worry about any of them not behaving correctly. But if you do wish to "see" the exponents for each function, then you could try the following
temp=cell(1,size(a,2));
temp{1,1}=1;
for k=2:size(a,2)
temp{k}=eval(sprintf('@(x) x.^%d',a(k)));
end
which would set temp to
temp =
[1] @(x)x.^2 @(x)x.^3
Note how we use sprintf to build the command string that we wish to evaluate with eval. Please be aware that using eval is sometimes discouraged as it can make debugging errors in code a little difficult.

1 Comment

I have tested my code. Indeed it works! Thank you for pointing this out.

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!