How to make inline function using for loop?

I need to make following function using "function handle"....
x=[x(1),x(2),x(3),...…,x(N)]……..Let say N=50
for i=1:1:N
fun(i)=@(x) 2*a + b + 4*c*d + 6*e %a, b ,c , d and e are iterative variables
end
a=[x(1),x(6),x(11),x(16),x(21),x(26),....,x(46)]
b=[x(2),x(7),x(12),x(17),x(22),x(27),.....x(47)]
c=[x(3),x(8),x(13),x(18),x(23),x(28),.....x(48)]
d=[x(4),x(9),x(14),x(19),x(24),x(29),.....x(49)]
e=[x(5),x(10),x(15),x(20),x(25),x(30),.....x(50)]
How can I write function using for loop?

2 Kommentare

Walter Roberson
Walter Roberson am 22 Sep. 2018
Why are you storing the same calculated anonymous function N times?
Sajjad Malik
Sajjad Malik am 22 Sep. 2018
Ultimately I use this function in "fmincon".....as an objective function...I tried other methods but could not find success.

Melden Sie sich an, um zu kommentieren.

 Akzeptierte Antwort

Walter Roberson
Walter Roberson am 22 Sep. 2018

0 Stimmen

fun = cell(N, 1);
F = @(x) 2*x(1:5:N) + x(2:5:N) + 4*x(3:5:N).*x(4:5:N) + 6*x(5:5:N);
fun(:) = {F};
Now fun stores N copies of the same function handle, each of which implements
@(x) 2*a + b + 4*c*d + 6*e
where a, b, c, d, e are short-hand for
a=[x(1),x(6),x(11),x(16),x(21),x(26),....,x(46)]
b=[x(2),x(7),x(12),x(17),x(22),x(27),.....x(47)]
c=[x(3),x(8),x(13),x(18),x(23),x(28),.....x(48)]
d=[x(4),x(9),x(14),x(19),x(24),x(29),.....x(49)]
e=[x(5),x(10),x(15),x(20),x(25),x(30),.....x(50)]
Each of the function handles will return a vector of length 50/5 = 10.

5 Kommentare

Sajjad Malik
Sajjad Malik am 23 Sep. 2018
Bearbeitet: Sajjad Malik am 23 Sep. 2018
sorry for late reply...Thanks for the answer...I used this method previously....Can you please answer me following two questions.....(1) How can this function be used in fmincon? ….. (2) How can I evaluate function using feval? ...Kindly remember that there are 50 variables in my code...named as x(1), x(2),....,x(50)….Regards
Walter Roberson
Walter Roberson am 23 Sep. 2018
You cannot use the function with fmincon because the objective function for fmincon needs to return a scalar.
Sajjad Malik
Sajjad Malik am 23 Sep. 2018
Exactly...you are right....Is there any other way to deal with this type of situation?...
Walter Roberson
Walter Roberson am 23 Sep. 2018
No. When your objective function returns a vector of results, then fmincon and most other minimizers are not appropriate. You would need something like gamultiobj() which tries to find pareto fronts.
Sajjad Malik
Sajjad Malik am 23 Sep. 2018
Thanks Walter

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Community Treasure Hunt

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

Start Hunting!

Translated by