Jack_The_Ripper
Jack_The_Ripper

Reputation: 703

Inputting a function on MATLAB

I have been trying to write a MATLAB code that can take in any function for optimization with as many variables as the user wants.

function Enter_Optimization_Code

clear all
clc

x=[];
U='';

n=input('Enter the number of variables= ')
U=input('Enter function with variables as x(1), x(2), x(3)..= ','s')
start=input('Enter coordinates of the starting point as [1,3,..]= ')

for i=1:n
    x(i)=start(i)
end

int(U)

The code is asking the user to enter the number of variables they want and then the function they want to optimize (I didnt write the optimization code yet). For now, I want the code to plug in the value of the starting point into the function and spit out the answer.

e.g. I am entering a function that is x(1)+x(2) and start point as [1,2]. This should cause the code to do the calculation of 1+2=3 and print 3. This is what's happening instead:

Enter the number of variables= 2

n =

     2

Enter function with variables as x(1), x(2), x(3)..= x(1)+x(2)

U =

x(1)+x(2)

Enter coordinates of the starting point as [1,3,..]= [1,2]

start =

     1     2


x =

     1


x =

     1     2

Undefined function 'int' for input arguments of type 'char'.

Error in Enter_Optimization_Code (line 17)

Can anybody solve this?

Upvotes: 0

Views: 375

Answers (2)

am304
am304

Reputation: 13876

If you are trying to integrate the function with the symbolic function int, you can't pass a string input to that function, it has to be a symbolic expression, check the documentation.

You probably need to do int(sym(U)) instead to convert the string U into a symbolic expression.

EDIT based on comments and using TroyHaskin's suggestion

Here's a version that should work. However, I'm not sure why this is a function, it should really be a script.

function Enter_Optimization_Code
% Not sure why you're using a function, this should really be a script

% clear all should only be used in scripts, not in functions
clc

% n=input('Enter the number of variables= '); not needed
U=input('Enter function with variables as x(1), x(2), x(3)..= ','s');
start=input('Enter coordinates of the starting point as [1,3,..]= ');

f = str2func(['@(x)',U]);
y = feval(f,start);

disp([U 'evaluated at x=([' num2str(start) ']) = ' num2str(y)])

Upvotes: 1

TroyHaskin
TroyHaskin

Reputation: 8401

If you want the user to enter the equation in this manner, you can convert the string to an anonymous function using str2func:

fun = str2func(['@(x)',U]);

This will work for function literals like x(1)-x(2)^x(3) and valid function calls my_opt(x).

Upvotes: 1

Related Questions