Convert strings to array of function handles

6 Ansichten (letzte 30 Tage)
ic_fly2
ic_fly2 am 30 Sep. 2014
Kommentiert: José-Luis am 2 Okt. 2014
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

Antworten (1)

José-Luis
José-Luis am 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)
  2 Kommentare
ic_fly2
ic_fly2 am 2 Okt. 2014
Thank you for the speedy reply, I much prefer your method to getting the loop part, unfortunately the output is still a string, which is not what i need to feed to the list of functions. For some reason matlab does not allow me to allocate rows or elements of the array nlcon individually but when written as a whole it accepts them. So the string still needs to be converted to normal input or however matlab calls that.
José-Luis
José-Luis am 2 Okt. 2014
I am not sure I follow. If you want an array of strings, then you could loop through every a value and generate the string as I show.
If you want to transform a string into a function, please look at str2func().
doc str2func

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Shifting and Sorting Matrices finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by