Question

Is there a function or technique for converting MATLAB's symbolic expressions to expressions that can be evaluated element-wise?

As an example, the command

a = solve('x^2 + a*x + b == 0')

gives the output

a = 
   (a^2 - 4*b)^(1/2)/2 - a/2
 - a/2 - (a^2 - 4*b)^(1/2)/2

The desired output, however, which allows a and b to be arrays, is

a = 
   (a.^2 - 4*b).^(1/2)/2 - a/2
 - a/2 - (a.^2 - 4*b).^(1/2)/2
Était-ce utile?

La solution

solve('x^2 + a*x + b == 0') returns a 2x1 sym. I understand you want to evaluate the solution for various a and b values. To do this, you first need to convert your sym to a function using matlabFunction.

s = solve('x^2 + a*x + b == 0');
f = matlabFunction(s);

Now f is a function of two input arguments a and b. Try it on two vectors of three a and b values:

f([1 2 3],[1 1 1])

and you will get a 2x3 array of the solutions.

You can also use subs to achieve what you want to do:

subs(s,{'a' 'b'},{[1 2 3 ] [1 1 1]})

will substitute [1 2 3] for a and [1 1 1 ] for b and return a 2x3 sym. If you want to evaluate it, just use eval:

eval(subs(s,{'a' 'b'},{[1 2 3 ] [1 1 1]}))

Autres conseils

To get just the string you are asking for, there exists a MATLAB function to do this. It is called vectorize.

See more information here in the MATLAB documentation. The function inserts a . before any ^, * or / in s. The result is a character string.

I believe you have several operations to convert.

you can actually replace it by (a.^2 - 4*b).^(1/2)/2 - a./2

I would suggest 3 different solutions, depending on how many different variables you have in the expressions:

  • If you only have less than a couple dozen variables, it might be easier to do a "CTRL-F" (search and replace), and replace every variable "var" by their equivalent "var." in your code. Make sure to check "whole word". This should take you less than a minute.
  • If you have less than a couple dozen variables, but the expressions split in several different files, you might want to download notepad++ and do the same thing. Notepadd++ adds an option of searching & replacing in folders and subfolders instead of files directly. This would save you a lot of time.
  • If you have a lot of different variables, you might want to look into regexp, and do a search and replace with a reg expression for each string that appears in the files. create a new matlab function that would implement regexprep the way you need it.

Edit: I just noticed that you need to be careful with the parenthesis.

(a.^2 - 4*b).^(1/2)/2 - a./2 works (a.^2 - 4*b.).^(1/2)/2 - a./2 does not work

so if you do the CTRL-F method, you will need to replace the "var.)" by "var)" at the end

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top