38 views (last 30 days)

I'm trying to use the composite simpsons 1/3 rule but the code is giving me an error message.

fx=1-exp(-x);

n = 5;

x = linspace(0, 4,1000);

h = (x(end) - x(1))/n; % width of each segment

x_simp = linspace(0, 4, n+1);

for k = 1:n

x_simp_begin(k) = x_simp(k);

x_simp_end(k) = x_simp(k+1);

x_simp_mid(k) = (x_simp_begin(k) + x_simp_end(k))/2;

fx_simp_begin(k) = fx(x_simp_begin(k));

fx_simp_end(k) = fx(x_simp_end(k));

fx_simp_mid(k) = fx(x_simp_mid(k));

I_simp_seg(k) = h/6*(fx_simp_begin(k) + 4*fx_simp_mid(k) + fx_simp_end(k));

end

I_simp = sum(I_simp_seg)

Error message:

Array indices must be positive integers or logical values.

John D'Errico
on 21 Nov 2020

Tell me, what is fx?

fx is NOT a function. It is a scalar, vector, or array. Whatever x was, fx is the same thing. If it NOT a function that you can evaluate at some point. So then, when you write

I_simp_seg = 1/6*(fx(0) + 4*fx(mid) + fx(4));

what does MATLAB do? It KNOWs that fx is a variable. It tries to index the variable at position 0. What did it tell you?

Array indices must be positive integers or logical values.

You need to learn how to write a FUNCTION that can be passed arguments. You MIGHT try a function handle.

doc function_handle

A simple example for your problem here would be

fx = @(x) 1-exp(-x);

VBBV
on 22 Nov 2020

Edited: VBBV
on 22 Nov 2020

syms x % define x as symbol

%x = linspace(0, 4,5);

fx=@(x) 1-exp(-x); % use function handle as D'Errico suggested

Then you can define the width of each segment inside loop as

for k = 1:n

x_simp_begin(k) = x_simp(k);

x_simp_end(k) = x_simp(k+1);

h = (x_simp_end(k) - x_simp_begin(k) )/n; % width of each segment

x_simp_mid(k) = (x_simp_begin(k) + x_simp_end(k))/2;

fx_simp_begin(k) = fx((x_simp_begin(k)));

fx_simp_end(k) = fx((x_simp_end(k)));

fx_simp_mid(k) = fx((x_simp_mid(k)));

I_simp_seg(k) = h/6*(fx_simp_begin(k) + 4*fx_simp_mid(k) + fx_simp_end(k));

end

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!
## 0 Comments

Sign in to comment.