how to convert handle to array
Show older comments
hello, it's my first post and i'm not very good in english, so soryy for my errors. I've got one problem with matlab. I've got a handle like a=@(x)( f1(x), f2(x),..,fn(x)) and i have to read one of function in handle to have something like this @(x)(f2(x)). is there any function to convert handle argument to structure where the functions will be in separate cells like [f1(x), f2,..fn]?
Answers (2)
Walter Roberson
on 29 Apr 2014
No, the closest is
indexat = @(expr, index) expr(index);
F2 = @(x) indexat(a(x), 2);
Star Strider
on 29 Apr 2014
Edited: Star Strider
on 29 Apr 2014
There is no one function, but it is easy enough. Since it is not obvious from your question what the individual functions return, you are correct in assigning them to Cell Arrays.
Note the use of ‘curly brackets’ { } to define the cell arrays in the assignment to a and the cell references in y1 and y2.
Example:
f1 = @(x) x^2;
f2 = @(x) 1:x;
a = @(x) [{f1(x)} {f2(x)}];
y = a(5)
y1 = y{1}
y2 = y{2}
produces:
y =
[25] [1x5 double]
y1 =
25
y2 =
1 2 3 4 5
4 Comments
Blazej
on 29 Apr 2014
Star Strider
on 29 Apr 2014
If all your functions are producing scalar outputs for a particular input, that is even easier. Use square brackets [ ] to create a vector (or matrix):
a=@(x) [x(1)^2, x(2)^2, 2* x(1)];
x = [3 5];
y = a(x)
produces:
y =
9 25 6
Blazej
on 29 Apr 2014
Star Strider
on 29 Apr 2014
Edited: Star Strider
on 29 Apr 2014
The
y = a(1)
assignment passes the value 1 to the anonymous function a and creates a cell array of function evaluations. The next two lines (assignments to y1 and y2) access individual elements of the cell array.
I am happy it does what you want it to!
Categories
Find more on Matrix Indexing 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!