1
\$\begingroup\$

I need to speed up this code: it creates a multilinear function. I considered the below methods but no idea which with the largest benefit.

  • replacing dummy variables with things such as anonymous functions
  • having all code in the same file (my instructor's hint)
  • improving the looping: getting rid of num2str
  • other?

I need to repeatedly create this kind of initialisations and I am trying to get it as fast as possible. It may be that the reason for the slowness of my code lies somewhere else, not this code, say it if you think so! There may be some elegant functional way to write this fast and more compactly. I already know that the whole code is probably slow because of the mlfnneg but in order to speed it up I need to make sure the bug is not early ie on this code aka during the initialisation of test-cases.

enter image description here

 %Creating a mlf to check the negativity of the multilinear function

 % Example: 0<x_i<i/Density
 lbs_str=containers.Map;  % I need variables here only to initialise mlf at the end
 ubs_str=containers.Map;
 terms=containers.Map;

 for i = 1:100
    i=num2str(i); % possible to make this more elegant? contairers.Map requires string
    lbs_str(i)=0;
    ubs_str(i)=i/100;
    terms(i)=struct('coeff',1,'vars',{{i}});
    % Tested catstruct [1] to append new terms to the mlf_terms but not intended:
    % it does not do {terms('1'), terms('2'),...} aka {terms.values}
 end

 lbs=mlfpoint(lbs_str);
 ubs=mlfpoint(ubs_str);
 mlf_terms=struct('const',0,'terms',{terms.values});
 mlf=mlfcreate(mlf_terms);

 mlfnneg(lbs,ubs,mlf)
\$\endgroup\$
2
\$\begingroup\$

You should be able to prevent casting to a string 100 times.

First create all strings in a cell array, then just loop over the strings.


Though it does not show up on the profiler, this looks higly dubious:

i=num2str(i)
ubs_str(i)=i/100;

Now you will get the character code of 'i' and divide that by 100.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.