开发者

Problem with a variable not changing value in MATLAB

开发者 https://www.devze.com 2023-03-10 04:55 出处:网络
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:

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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消