Alternative to EVAL string expressions in optimization

Hi,
I have a huge matrix, each element is a string like "16*q^2+4*q", i call it new_sol_array, now i want to define multiple optimconstr object with each row one set of constraints. This is what i did:
constr= optimconstr(M,N);
for i=1:rows
for j =1:column
constr(i,j)=eval(new_sol_array(i,j)+'==0');
end
end
As you would see, this is extremely slow. Is there a better alternative to do the same thing? i have read some of the answers about eval on this website yet did not find anything relevant enough to my problem.
Thank you so much!!!

 채택된 답변

Walter Roberson
Walter Roberson 2022년 5월 31일
Instead of eval() everything, use file operations to emit a file along the lines of
constr = [
EQN, EQN,... EQN
EQN, EQN,... EQN
]
along with a function header. Then "clear" the name of the file. Then invoke the file as a function passing in q and whatever else is required
This reduces the burden by not needing to eval() each one individually.

댓글 수: 4

Kylekk
Kylekk 2022년 5월 31일
편집: Kylekk 2022년 5월 31일
Thank you so much for your comment Walter! I'm not sure i understand your answer correctly so i'm just gonna repeat what you said and please correct me if i'm wrong.
1. Write a text file maybe with content like
constr = [
16*q^2+4*q==0, 25*q*t+20*t==0,... EQN
EQN, EQN,... EQN
]
2. Read this text file, substitute in variables (this step i'm actually not sure how to do, could you be more specific?)
3. Evaluate this one-hell-of-a-long line of command only once by eval.
Is that so? Appreciate it!
Just to update. I tried
temp = new_sol_array+'==0';
temp = join(join(temp,2),';',1);
temp = 'constr=['+temp+']';
eval(temp);
It took me less than 3 min to assign 10000 by 10 constraints. Not perfect but definitely acceptable.
Stephen23
Stephen23 2022년 5월 31일
편집: Stephen23 2022년 5월 31일
  1. yes
  2. no
  3. no
Did you try writing a function file and calling it, as Walter Roberson described?
Thank you Stephen, I did not do that simply because I don't get the idea. What kind of function file are you talking about? I have only a string array, why would a function takes variable names as input help?

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

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Characters and Strings에 대해 자세히 알아보기

제품

질문:

2022년 5월 30일

댓글:

2022년 5월 31일

Community Treasure Hunt

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

Start Hunting!

Translated by