0

So I have one problem with my code, which is that one variable is not working as it's supposed to do. Here are the codes I'm using:

format long
f = inline('-x.^2');
for i = 0:10
    [I(i+1) h(i+1) tid(i+1)] = trapets(f,0,1,2^i);
end

for i = 0:10
    trunk(i+1) = I(i+1) - log(2);
end

hold on
grid on
plot(log(h),log(trunk),'r+')

t = -7:0;
c = polyfit(log(h),log(trunk),1);
yy = polyval(c,t);
plot(t,yy)
grid off
hold off

koefficienter = real(c)

and also this:

function [ I,h,tid ] = trapets(f,a,b,n )
h=(b-a)/n;

tic;
I=(f(a)+f(b));
for k=2:2:n-2
    I = I+2*f(a+k*h);
end

for k = 1:2:n-1
    I = I + 4*f(a+k*h);
end

I = I * h/3;
tid = toc;
end

So the problem here is that the variable I is not changing value. It gets 11 values when I run the first code (I don't run the last code I wrote, it's only used by the first one), but the values are all the same. I don't know if the problem is that the variable n, which I use in the the second code, never change value, although I'm trying to do that with the "2^i" part in "trapets(f,0,1,2^i)". If the case is that n never change value, is there a solution to do that?

And if the problem is not the variable n, why doesn't the variable I change value in the code?

6
  • 2
    @nisse: Here's a general tip: Do not name your variables as l or l1, l2, etc. It's really hard to distinguish it from I or 1 in certain fonts. Commented Jun 4, 2011 at 18:49
  • Okay, thanks. As a clerification: k = 1:2:n-1 in the second code it says n-1, as the number one and not the variable 'I'. Commented Jun 4, 2011 at 19:06
  • @yoda I didn't make any variable changes. Commented Jun 4, 2011 at 19:45
  • okay, so what did just happen? Commented Jun 4, 2011 at 20:04
  • 1
    @trutheality: I apologize, it was my mistake... I saw the comparison and this is what I saw everywhere: imgur.com/a/iD1OR (the top being the original and the bottom being your edit) and thought you had changed it from l to I, when it actually was the difference between normal font and monospaced font. This fumble on my part only further reinforces my first comment to the OP! Commented Jun 4, 2011 at 20:08

1 Answer 1

1

After running your program I found out the I always equals -1/h after the for loops, which makes I = I * h/3; always give you the same result.

Sign up to request clarification or add additional context in comments.

1 Comment

Okay, I just found out that I get different values for 'I' if i change the function to something with a higher power. Thanks for all the help anyway.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.