How to not use for loop
조회 수: 10 (최근 30일)
이전 댓글 표시
Hi, I have a function that I am trying to get rid of the for loop and rewrite the function so that it doesnt use any loops. I have looked on various links like the Vector Creation (https://au.mathworks.com/help/matlab/ref/colon.html) and Vectorisation (https://au.mathworks.com/help/matlab/matlab_prog/vectorization.html) but I still cant get it to work. Below I have the function with the for loop.
function dfdx = ddx(f, h)
% Add description, name, date, inputs, outputs
dfdx = nan(size(f));
dfdx(1) = (f(2) - f(1))/h;
for j = 2:length(f)-1;
dfdx(j) = 0.5*(f(j+1) - f(j-1))/h;
end
dfdx(end) = (f(end) - f(end-1))/h;
And here is the code to call the function
format compact
a = randn(2, 1)
x = linspace(-1, 1, 20) % equispaced x
f = a(1) + a(2)*x % function values
dfdx = ddx(f, x(2)-x(1)) % derivatives should be exact for linear
computeError = a(2) - dfdx % should be zeros to 1e-15
댓글 수: 0
채택된 답변
Star Strider
2022년 9월 7일
편집: Star Strider
2022년 9월 7일
Try something like this —
format compact
a = randn(2, 1)
x = linspace(-1, 1, 20) % equispaced x
f = a(1) + a(2)*x % function values
dfdx = ddx(f, x(2)-x(1)) % derivatives should be exact for linear
computeError = a(2) - dfdx % should be zeros to 1e-15
function dfdx = ddx(f,h)
dfdx(1) = (f(2) - f(1))/h;
dfdx(2:numel(f)) = (f(2:end) - f(1:end-1))/h;
end
EDIT — The gradient function already exists to do this, however I’m assuming here that you want to write your own function to do the numerical derivative.
.
댓글 수: 4
Star Strider
2022년 9월 7일
@Declan — As always, my pleasure!
@Torsten —
I checked it against the gradient function and both gave the same result.
That was my criterion —
format compact
a = randn(2, 1)
x = linspace(-1, 1, 20) % equispaced x
f = a(1) + a(2)*x % function values
dfdx = ddx(f, x(2)-x(1)) % derivatives should be exact for linear
computeError = a(2) - dfdx % should be zeros to 1e-15
CompareResults = ["gradient" gradient(f, x(2)-x(1)); "ddx" dfdx]
function dfdx = ddx(f,h)
dfdx(1) = (f(2) - f(1))/h;
dfdx(2:numel(f)) = (f(2:end) - f(1:end-1))/h;
end
.
Torsten
2022년 9월 7일
Yes, for linear functions, centered and forward differencing to approximate the derivative give the same result.
참고 항목
카테고리
Help Center 및 File Exchange에서 Function Creation에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!