How to not use for loop
Show older comments
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
Accepted Answer
More Answers (1)
Categories
Find more on MATLAB in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!