Efficient operation on individual matrix rows

조회 수: 3 (최근 30일)
Chris B
Chris B 2018년 5월 22일
댓글: Chris B 2018년 5월 23일
Hello,
I'm searching for a way to apply the Jacobian function to each row of a matrix. Essentially I need to access each row of a matrix and apply a function. I could use a "for loop" which is quite slow:
for i=1:size(a,1)
tmp = jacobian(a(i,:),b);
result=cat(1,result,tmp);
end
I also found this solution:
function dNdv = matjacobian(N,v)
rz = arrayfun(@(ii)jacobian(N(ii,:),v),(1:numel(N(:,1))).','un',0);
dNdv = cat(1,rz{:});
end
The second solution is faster but I'm wondering if there is a more efficient way. Or even a way to apply the jacobian to a multi row matrix.
Thanks in advance,
Chris

채택된 답변

Stephen23
Stephen23 2018년 5월 22일
편집: Stephen23 2018년 5월 22일
"I could use a "for loop" which is quite slow:"
The problem is not the for loop, but the fact that you expand the array result on each loop iteration. Expanding arrays is slow. Read this to know why:
Using a loop (with a properly preallocated output) will be faster than using arrayfun. You can simply preallocate the output array to be the correct size before the loop, and your code will be quite fast:
out = nan(...); % defined to be the final size!
for k = ...
...
out(k,...) = ...
end
the correct size to use for preallocation depends on a and b: I am sure that can figure that out.
  댓글 수: 1
Chris B
Chris B 2018년 5월 23일
Perfect, that worked. The for loop with preallocation is indeed faster. Thanks.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by