yalmip / YALMIP

MATLAB toolbox for optimization modeling
https://yalmip.github.io/
Other
478 stars 137 forks source link

sdpvar2function #1396

Closed Gedlex closed 4 months ago

Gedlex commented 5 months ago

I was looking into a solution on how to create a matlab function from an sdpvar object. I had to realise that there are only hacks so far. So I thought one could possible add this hack to the library to reduce the effort for useres a bit.

Here is a suggestion for a functionality that could work more or less reliably:

function f_handle = sdpvar2function(varargin)
    % Copy sdpvar to function workspace
    for i = 1:nargin
        if ~isa(varargin{i},'sdpvar')
            error('All input arguments must be sdpvar objects')
        elseif i==1
            continue
        end
        var_name = inputname(i);
        eval([var_name,'=varargin{i};'])
    end

    % Convert sdpvar to string
    svar = sdisplay(varargin{1});

    if any(contains(svar,'internal'))
        error(['Not enough input arguments. Provide all sdpvar used in ',inputname(1),' as a function input.'])
    end

    % Create symbolic variables from input
    clearvars('-except','varargin','svar')
    inputs = cell(nargin-1,1);
    for i = 2:nargin
        var_name = inputname(i);
        eval([var_name,'=sym(var_name, size(varargin{i}));'])
        inputs{i-1} = eval(var_name);
    end

    % Convert string to symbolic expression
    f_sim = sym('f_sim', size(svar));
    for i = 1:numel(f_sim)
        f_sim(i) = eval(svar{i});
    end

    % Convert symbolic expression to function
    f_handle = matlabFunction(f_sim,'Vars',inputs);
end
johanlofberg commented 5 months ago

Feel free to make a pull request.

function name sounds wrong though, as this is not a generic function, but something relying on the syms toolbox

Gedlex commented 5 months ago

So what would you suggest as function name?

johanlofberg commented 5 months ago

sdpvar2syms, or make it a method for @sdpvar and simply call it syms

Gedlex commented 5 months ago

Okay, I will do it as soon as I find the time