cagriaydin
cagriaydin

Reputation: 1

Matlab simple loop for different function variables

I wrote a simple MatLab script to evaluate forward, backward and central difference approximations of first and second derivatives for a spesific function

(y = x^3-5x)

at two different x values

(x=0.5 and x = 1.5)

and for 7 different step sizes h and compare the relative errors of the approximations to the analytical derivatives.

However, i need to enter x and h values manually every time. Question is, how do I create a loop for 7 different h values and 2 different x values and get all the results as a matrix?

clc
clear all
close all

h = 0.00001;
x1 = 0.5;

y = @(x) x.^3 - 5*x;
dy = @(x) 3*x.^2 - 5;
ddy = @(x) 6*x;
d1 = dy(x1);
d2 = ddy(x1);

%Forward Differencing

f1 = (y(x1+h) - y(x1))/h;
f2 = (y(x1+2*h) - 2*y(x1+h) + y(x1))/(h.^2);

%Central Differencing

c1 = (y(x1+h)-y(x1-h))/(2*h);
c2 = (y(x1+h)-2*y(x1)+y(x1-h))/(h.^2);

% Backward Differencing

b1 = (y(x1) - y(x1-h))/h;
b2 = (y(x1)-2*y(x1-h)+y(x1-2*h))/(h.^2);

% Relative Errors

ForwardError1 = (f1 - dy(x1))/dy(x1);
ForwardError2 = (f2 - ddy(x1))/ddy(x1);

CentralError1 = (c1 - dy(x1))/dy(x1);
CentralError2 = (c2 - ddy(x1))/ddy(x1);

BackwardError1 = (b1 - dy(x1))/dy(x1);
BackwardError2 = (b2 - ddy(x1))/ddy(x1);

Upvotes: 0

Views: 34

Answers (1)

buzjwa
buzjwa

Reputation: 2652

You don't need a loop. You can use meshgrid to create all combinations of your arguments (x and h in your case) and use these as inputs to your functions.

To get combinations of x = [0.5, 1.5] and h=0.00001:0.00001:0.00007 (I assume since you did not specify h values in the question), you would do:

[x, h] = meshgrid([0.5, 1.5], 0.00001:0.00001:0.00007);
y = @(x) x.^3 - 5*x;
f1 = (y(x1+h) - y(x1))./h;

Here x,h are matrices of size 7x2, and so is the result f1. Note that / was changed to ./ as h is a matrix and we want per-element operations.

Upvotes: 1

Related Questions