View Full Version : Question about a matlab program
ramin86
Sep11-04, 02:31 AM
m = 0;
x(1)=10;
for k = 2:3:11
m = m+1;
x(m+1) = x(m) + k^2;
end
Its a simple program, but for some reason I cannot explain how it works, I was wondering if I can get some help.
TenaliRaman
Sep11-04, 03:17 AM
m = 0;
%initialisation of m
x(1)=10;
%initialisation of x(1)
for k = 2:3:11
%k goes from 2 to 11 with step size of 3
%i.e k will have values 2,5,8,11
m = m+1;
%increment value of m
x(m+1) = x(m) + k^2;
%calculate next value of x_array
end
%end of for loop
-- AI
ramin86
Sep11-04, 12:39 PM
Well, the only thing I really don't get is x(m+1) = x(m) + k^2;
The calculated values are 10, 14, 39, 103, 224, how are these values calculated through that statement?
What it's doing is increasing the size of the 'x' array.
x(1) is 10
m is 1
The first iteration of the 'for' loop, k is 2
x(m+1) = = x(m) + k^2;
That means that its taking the value in x(m), which is x(1), which is 10; it is adding k^2 or 4 to it (14)
and storing it in x(m+1), x(2), or the second slot in the 'x' array.
It then proceeds on down the line.
Might I suggest you familiarize yourself with the debugging commands?
If you hit 'set breakpoint' (I think it's F12) and then run, the program will pause at that line. You can then either mouse over the variables in question and let you see what's stored there, or you can doubleclick on the variables in the Matlab main page's workspace to bring up a dialog.
To continue to the next breakpoint (or end of the program) i think the key is F5 (continue)
ramin86
Sep11-04, 09:54 PM
Alright, now I understand it. My next question relates to the following program:
x = 0;
k = 0;
sum = 0;
while x < 2000
k = k + 1;
x = 2^k;
end
I was asked to find the number of terms for the series to exceed 2000. But now, I am asked to find the sum of those terms. How would I do that? I know its rather simple, but for whatever reason I've always had problems with loops when dealing with programming.
vBulletin® v3.7.6, Copyright ©2000-2009, Jelsoft Enterprises Ltd.