Convert strings to array of function handles
Show older comments
Hi, I'm using the opti platform and for NLP problems I need constraints in the following form:
nlcon = @(x) [ a(1)*x(1)^3 - b(2)*x(2);...
a(2)*x(2)^3 - b(3)*x(3);...
a(3)*x(3)^3 - b(1)*x(1)];
So I have small loop to generate these as strings:
a = [1 2 3];
b = [2 6 4 ];
pile = [];
for i = 1:length(a)
if i <= length(a)-1
text = [' a(' num2str(i) ')*x(' num2str(i) ')^3 - b(' num2str(i+1) ')*x(' num2str(i+1) ')'];
else
text = [' a(' num2str(i) ')*x(' num2str(i) ')^3 - b(1)*x(1)'];
end
pile = [pile; text];
end
And pile is the array of polynomials that i would like to form nlcon out of. Now if display or print pile and copy and past the result back into my script it works, but I'm certain there is a more elegant and efficient method. Cell arrays don't work, or at least I've had no success getting opti to accept them.
Kind regards,
ic_fly2
Answers (1)
José-Luis
on 30 Sep 2014
a = [1 2 3];
b = circshift(a,[0 -1]);
all_num = [a;a;b;b];
argument = sprintf('a(%i)*x(%i)^3 - b(%i)*x(%i)\r\n',all_num)
Categories
Find more on Shifting and Sorting Matrices 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!