diff function taking very long time while differentiating symbolic expressions

조회 수: 3 (최근 30일)
Hello all,
I need to make a Jacobian matrix where both the function (f) array and the variable (y) array are of 5420-by-1. f is an array of symbolic expressions. The sample code is below.
for i=1:5420
for j=1:5420
jacobian(i,j)=diff(f(i), y(j)); % Finding the jacobian element
end
end
After running a few iterations, it seems like it will take more than 5 days. Is there any other way to do that so it should take less time? Thanks in advance.
  댓글 수: 2
Walter Roberson
Walter Roberson 2020년 7월 23일
It is not clear why you are not using the jacobian() function
M Al Mamun
M Al Mamun 2020년 7월 24일
Thanks for your quick reply. Yeah, the jacobian fauction works with great speed. However, I wanted to write the code from the elementary level.

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

채택된 답변

Walter Roberson
Walter Roberson 2020년 7월 23일
Potentially faster:
numf = length(f);
numy = length(y);
Jac = zeros(numf, numy, 'sym');
for i = 1 : numf
thisf = f(i);
thesevars = symvar(thisf);
[~, varidx] = ismember(thesevars, y); %convert variable names to indices
for j = varidx
Jac(i, j) = diff(thisf, y(j));
end
end
What this does is query each f element for the unbound variables present in it, and then only tries to differentiate with respect to those variables.
In the form written it will fail if there are unbound variables that are not listed in y; the fix would not be difficult.
  댓글 수: 1
M Al Mamun
M Al Mamun 2020년 7월 24일
Thanks a lot Walter. This is what I was actually looking for. It is working perfectly and taking very less time compared to my previous approach.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Symbolic Variables, Expressions, Functions, and Preferences에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by