I keep getting 'Index exceeds array bounds.' my code doesn't like r(i)

2 vues (au cours des 30 derniers jours)
%function [int_ft] = gerberdolan_jessica_hw09_int(t, f)
%INPUT:
%t = vector of t values at which the function is provided
%f = vector of values of the function at the points contained in t
%OUTPUT:
%int_ft = value of integral
%start this function as a script with the following test senario
t = [0 pi/4 pi/2 3*pi/4 pi]
f = cos(t)+5
for i = 1:(length(t)-1)
t = t(i);
r(i) = f(i).*(t(i+1)-t(i))
%((t(1+1)-t(i)) is delta x
%f(t(i)) is the base rantagle for the retangular rule
%r is rectangle
tr(i) = (f(t(i))-f(t(i+1)))*(t(1+1)-t(i))*1/2
%tr is the triangle on top
%(f(t(i))-f(t(i+1))) is the height difference
%(t(1+1)-t(i)) is delta x
%1/2 is to make it a triangle
a_of_trap(i) = r(i) + tr(i)
%area of trapizoid is the rectangle plus the triangle
end
int_ft = sum(a_of_trap)
  2 commentaires
Adam Danz
Adam Danz le 28 Avr 2021
@Sudhaunsh Deshpande, I'd be happy to address your question once you've posted it. You can copy the URL to your new question here or tag me with the @ symbol to bring it to my attention.

Connectez-vous pour commenter.

Réponse acceptée

Adam Danz
Adam Danz le 13 Nov 2018
Modifié(e) : Adam Danz le 13 Nov 2018
Initially in your code, t is a vector.
t = [0 pi/4 pi/2 3*pi/4 pi]
t =
0 0.7854 1.5708 2.3562 3.1416
Then within your i loop, you overwrite t as a scalar.
t = t(i)
t =
0
Immediately after this, you try to grab the 2nd element of t even though t now only has 1 element. This is why the index (i+1) exceed array bounds. Because at this point, t is only 1 element long.
r(i) = f(i).*(t(i+1)-t(i))

Plus de réponses (1)

Guillaume
Guillaume le 13 Nov 2018
"my code doesn't like r(i)"
There's no liking involved. Your code does exactly what you tell it to. If you tell it to do something impossible it's not going to work.
I haven't looked further than
t = t(i);
to know that your code is never going to work. That line replace the whole vector t by a scalar, such that indexing t after that is always going to be an error.
Note that you can easily debug your own code which would be the best way for you to understand where you're going wrong. Step through your code one line at a time in the debugger. See what happens to your variables after each statement and check that it conforms to your expectations.
  1 commentaire
Jessica Gerberdolan
Jessica Gerberdolan le 13 Nov 2018
I appreciate you help! I have been attempting to de-bug my code for over thirty minutes now and I figured I needed an extra pair of eyes

Connectez-vous pour commenter.

Catégories

En savoir plus sur Programming dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by