min and max Functions Breaking After Conversion From Symbolic to MATLAB Function
조회 수: 4 (최근 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!