Convert strings to array of function handles

조회 수: 6 (최근 30일)
ic_fly2
ic_fly2 2014년 9월 30일
댓글: José-Luis 2014년 10월 2일
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

답변 (1개)

José-Luis
José-Luis 2014년 9월 30일
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
ic_fly2
ic_fly2 2014년 10월 2일
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 2014년 10월 2일
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

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Shifting and Sorting Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by