is it possible to differentiate max function?

조회 수: 6 (최근 30일)
Frank Oosterveld
Frank Oosterveld 2018년 12월 3일
편집: Walter Roberson 2023년 2월 17일
Hi,
Is it possible with the basic matlab functions to numerically differentiate a max function? This is what I tried, but did not work: 'Error using symengine, Input arguments must be convertible to floating-point numbers.'
r_par = 100;
R = 3;
P = @(x1,x2) r_par/2*(max(0,x1^2 + x2^2 - R^2))^2
gP = gradient(P, [x1, x2]);
gF = matlabFunction(gP);
x = [1 2];
x1 = x(1);
x2 = x(2);
ans = P(x1,x2)

답변 (1개)

Walter Roberson
Walter Roberson 2018년 12월 3일
편집: Walter Roberson 2018년 12월 3일
max() is not defined for symbolic . recode in terms of piecewise
Max = @(aa,bb) piecewise(aa>bb,aa,bb)
Note that matlabFunction can only handle piecewise if you tell it to write to aa file and even then the result will not be vectorized .
  댓글 수: 6
Alec Jacobson
Alec Jacobson 2023년 2월 17일
편집: Alec Jacobson 2023년 2월 17일
yeah, I wouldn't mind needing to specify the ComparisonMethod or if it determined that based on assumptions to deal with real vs. complex input (e.g., through an error for complex).
Meanwhile, the frustrating thing I'm finding about piecewise is that it gets confused with float inputs:
a = 1;
b = 2;
piecewise(a<b,a,b)
Maybe it's only defined for symbolic? That makes it difficult to prototype mixing numeric and symbolic code (which I see as a huge advantage of matlab vs. maple etc.)
Walter Roberson
Walter Roberson 2023년 2월 17일
편집: Walter Roberson 2023년 2월 17일
In the time since I wrote the original answer, MATLAB added a symbolic max() and min() as place-holders that wait until the question is decidable.
syms aa bb
max(aa, bb)
ans = 
So now you can
syms x1 x2
r_par = 100;
R = 3;
P = @(x1,x2) r_par/2*(max(0,x1^2 + x2^2 - R^2))^2
P = function_handle with value:
@(x1,x2)r_par/2*(max(0,x1^2+x2^2-R^2))^2
But you cannot call gradient() because that looks for numeric inputs, so you call diff()
gP = [diff(P, x1), diff(P, x2)]
gP = 
and then you can see that matlabFunction gets confused and thinks that x1 and x2 are the stride counts in numeric diff calls...
matlabFunction(gP)
ans = function_handle with value:
@(x1,x2)[diff(max([0.0,x1.^2+x2.^2-9.0],[],2,'omitnan'),x1).*max([0.0,x1.^2+x2.^2-9.0],[],2,'omitnan').*1.0e+2,diff(max([0.0,x1.^2+x2.^2-9.0],[],2,'omitnan'),x2).*max([0.0,x1.^2+x2.^2-9.0],[],2,'omitnan').*1.0e+2]

댓글을 달려면 로그인하십시오.

제품


릴리스

R2018a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by