How to not use for loop
8 ビュー (過去 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!