min and max Functions Breaking After Conversion From Symbolic to MATLAB Function
1 回表示 (過去 30 日間)
古いコメントを表示
If I have a function whose values I want to constrain between some minimum and maximum values, I can use the min and max commands. This works for both function handles and symbolic functions. However, I need to transform a symbolic function that uses min and max into a MATLAB function handle, and it is not working. For example, in the code below, I would expect to get 1, 1, 4, 5, 5, either vertically or horizontally concatenated depending on the input. But I don’t. Can someone advise me on how to get the symbolic version of the function into a MATLAB handle in a way that will produce results consistent with the symbolic (and original) version?
Thank you in advance.
t = 0:4
orig_fun = @(x) max(1, min(5, x.^2))
syms sym_fun(x)
sym_fun(x) = sym(orig_fun)
mat_fun = matlabFunction(sym_fun)
disp(' ')
disp('In a row:')
orig_fun(t)
double(sym_fun(t))
mat_fun(t)
disp(' ')
disp('In a column:')
orig_fun(t')
double(sym_fun(t'))
mat_fun(t')
0 件のコメント
採用された回答
Walter Roberson
2023 年 6 月 1 日
Symbolic variables (that are not symmatrix) are scalars. For scalar x, min(5,x) is the same as min([5,x])
Symbolic operations assume scalar. For example y*x assumes scalar x y and will rewrite to x*y if it makes for better presentation or easier internal operations (canonical internal representation for efficiency).
Any availability to replace variables with multiple values in the function handle is whatever is implemented by matlabFunction based on the expressions that reach it, and it does not try very hard at all. For example [1, x; 2, x.^2] will probably be transformed into a reshape(MATRIX,2,2) which will fail if the inputs are non-scalar.
Do not expect vector behaviour of symbolic variables; do not write symbolic code that is expected to work on vectors that are variable length (other than some element-by-element operations).
You can use vectors of symbols of definite length in combination with matlabFunction 'vars' option to pack the values into a single parameter... but if you need variable length vectors then expect trouble.
3 件のコメント
Walter Roberson
2023 年 6 月 1 日
syms x
sym_fun(x) = x.^2
% Here's where there might be symbolic stuff done on the function, so I
% don't know exactly what it will look like when it is time to put it back
% into a function handle.
mat_fun = matlabFunction(sym_fun)
BOUND15 = @(X) max(1, min(5, X))
mat_fun = @(X) BOUND15(mat_fun(X))
t = 0:4
mat_fun(t)
その他の回答 (0 件)
参考
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!