Matlab: creating a character vector

I am trying to create a function using the symbolic toolbar in Matlab. I'm having trouble creating a character vector (not a vector of symbolic variables). Do you guys know how to do this without creating or editing a text matlab file in your path?

  • * After creating symbolic variables and all that I use 'matlabFunction' to create and save a function.

Example:

Functions:

function f=test1(x,a) { f=x(1)/a(1)+x(2)/a(2); } 

the code:

 a = sym('a', [1 2]); x = sym('x', [1 2]); % f(x, a) = sym('f(x, a)'); r=x(1)/a(1)+x(2)/a(2); % f(x,a)=r; % handle=matlabFunction(f(x,a),'file','test1'); handle=matlabFunction(r,'file','test1'); 
  • The problem is that the above code creates a function with a set of input arguments (x1, x2, a1, a2) instead of (x, a), and I cannot change the shape of the input arguments, it must be uniform.
  • In fact, I am trying to write a function that will create a polynomial of a certain degree and save it in a way, so that I can use β€œeval” (which does not support watering) with it, but it will probably be useful for more.
+4
source share
1 answer

Try:

 >> x = sym('x',[1 2]) x = [ x1, x2] >> x(1) ans = x1 >> x(2) ans = x2 >> whos x Name Size Bytes Class Attributes x 1x2 112 sym 

This is similar to the entry:

 >> syms a1 a2 >> a = [a1 a2] 

EDIT:

First, we create an expression from symbolic variables:

 a = sym('a', [1 2]); x = sym('x', [1 2]); expr = x(1)/a(1)+x(2)/a(2); 

Then we convert it to the regular MATLAB function:

 fh = matlabFunction(expr, 'file','test1', 'vars',{a,x}); 

Function Generated:

 function expr = test1(in1,in2) a1 = in1(:,1); a2 = in1(:,2); x1 = in2(:,1); x2 = in2(:,2); expr = x1./a1+x2./a2; end 

Initially, I was thinking about using regular expressions to fix the created function descriptor. This is a much messier hack, so I recommend using the previous approach:

 % convert to a function handle as string fh = matlabFunction(expr); str = char(fh); % separate the header from the body of the function handle T = regexp(char(fh), '@\((.*)\)(.*)', 'tokens', 'once'); [args,body] = deal(T{:}); % extract the name of the unique arguments (without the index number) args = regexp(args, '(\w+)\d+', 'tokens'); args = unique([args{:}], 'stable'); % convert arguments from: x1 into x(1) r = sprintf('%s|', args{:}); r = r(1:end-1); body = regexprep(body, ['(' r ')(\d+)'], '$1($2)'); % build the arguments list of the new function: @(a,b,c) head = sprintf('%s,', args{:}); head = head(1:end-1); % put things back together to form a function handle f = str2func(['@(' head ') ' body]) 

Resulting function descriptor:

 >> f f = @(a,x)x(1)./a(1)+x(2)./a(2) 
+5
source

Source: https://habr.com/ru/post/1500895/


All Articles