Index exceeds matrix dimensions
16 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Hello, I am having trouble with my code. It keeps on giving me the "Index exceeds matrix dimensions" error and tells me
Error in A9TRAPOchoa (line 20) n=n(in)
Is there any way to fix this?
function I=A9TRAPOchoa(fun,interval,n)
%Inputs:
%integ-the function to be evaluated
%interval-[a b]=the integration limits
%n-number of segments
%Outputs:
%I-integral estimate
fun=@(x) (4.*x.^3)-(42.*x)+700;
interval=[0 10];
n=[2 3 4 5 10 15 20 30 40 50];
for in=1:length(n)
n=n(in);
end
a=interval(1);
b=interval(2);
x=a;
h=(b-a)/n;
s=fun(a);
for j=1:n-1
x=x+h;
s=s+(2*fun(x));
end
s=s+fun(b);
I=(h/2)./s;
end
Thank you for your time.
0 comentarios
Respuestas (1)
ANKUR KUMAR
el 5 de Dic. de 2017
Editada: ANKUR KUMAR
el 5 de Dic. de 2017
There are few corrections which you have to do.
1. You have defined fun in between of the function. So, there is no need to write in the function call. So, your first line reduces to
function I=A9TRAPOchoa(interval,n)
2. I could not able to understand the reason behind using this code in between of the program.
for in=1:length(n)
n=n(in);
end
You can delete these 3 lines. And by deleting these lines, there is no need to put n in the function call. So, now your first line reduces to
function I=A9TRAPOchoa(interval)
3. Instead of writing
x=a; h=(b-a)/n; s=fun(a);
You should to write
x=a; h=(b-a)./n; s=fun(a);
Now, your function is correct. For, reference, I am pasting the correct function by omitting your errors.
function I=A9TRAPOchoa(interval)
fun=@(x) (4.*x.^3)-(42.*x)+700;
interval=[0 10];
n=[2 3 4 5 10 15 20 30 40 50];
a=interval(1);
b=interval(2);
x=a; h=(b-a)./n; s=fun(a);
for j=1:n-1
x=x+h;
s=s+(2*fun(x));
end
s=s+fun(b);
I=(h/2)./s;
end
Now, if you type A9TRAPOchoa([5 8]) in command window, then you will get your answer.
NOTE: You have already defined n in between of the function. So, if you need to change every time, then delete the line, where you have defined n in the function and put n in the function call. If you want to change n every time, then use
function I=A9TRAPOchoa(interval,n)
fun=@(x) (4.*x.^3)-(42.*x)+700;
interval=[0 10];
a=interval(1);
b=interval(2);
x=a; h=(b-a)./n; s=fun(a);
for j=1:n-1
x=x+h;
s=s+(2*fun(x));
end
s=s+fun(b);
I=(h/2)./s;
end
Type A9TRAPOchoa([5 8],[1:45]) in command window to get the desired result.
0 comentarios
Ver también
Categorías
Más información sobre Entering Commands 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!