How to not use for loop
13 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Declan
el 7 de Sept. de 2022
Comentada: Torsten
el 7 de Sept. de 2022
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 comentarios
Respuesta aceptada
Star Strider
el 7 de Sept. de 2022
Editada: Star Strider
el 7 de Sept. de 2022
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 comentarios
Star Strider
el 7 de Sept. de 2022
@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
el 7 de Sept. de 2022
Yes, for linear functions, centered and forward differencing to approximate the derivative give the same result.
Ver también
Categorías
Más información sobre Function Creation en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!