# Thread: help with matlab coursework...i keep receiving the error message!

1. ## help with matlab coursework...i keep receiving the error message!

hello...
consider the number (G-numbers) G(n) that are defined for all non-negative intergers n by
G(0) = 0
G(1) = 1
G(2) = 1
G(n) = 3G(n-1) - G(n-2) - G(n-3), for n>1.
Write a matlab function, gseq(n), that will calculate G(n).

I have tried and tried to do this but keep getting it wrong, and dont know exactly where i am going wrong. This is what i have tried, could anyone please tell me where i have gone wrong? thankyoU!!
function g = gseq(n)
%G(n) Calculates nth gseq number.

if n < 0
error(
'n is less than zero');
end
if
n < 2
f = n;
n = 2
f = n-1;
else
%tmp is a temporary vecoter used to store the gseq numbers.
tmp(1) = 0;
tmp(2) = 1;
tmp(3) = 1;
for inum = 3:n
tmp(inum+1) = 3*tmp(inum) - tmp(inum-2) - tmp(inum-2);
end
g = tmp(n+1);
end

2. Originally Posted by ero
hello...
consider the number (G-numbers) G(n) that are defined for all non-negative intergers n by
G(0) = 0
G(1) = 1
G(2) = 1
G(n) = 3G(n-1) - G(n-2) - G(n-3), for n>1.
Write a matlab function, gseq(n), that will calculate G(n).

I have tried and tried to do this but keep getting it wrong, and dont know exactly where i am going wrong. This is what i have tried, could anyone please tell me where i have gone wrong? thankyoU!!
function g = gseq(n)
%G(n) Calculates nth gseq number.

if n < 0
error(
'n is less than zero');
end
if
n < 2
f = n;
n = 2
f = n-1;
else
%tmp is a temporary vecoter used to store the gseq numbers.
tmp(1) = 0;
tmp(2) = 1;
tmp(3) = 1;
for inum = 3:n
tmp(inum+1) = 3*tmp(inum) - tmp(inum-2) - tmp(inum-2);
end
g = tmp(n+1);
end
I'm not much for Mathlab coding, but check this line out:
tmp(inum + 1) = 3*tmp(inum) - tmp(inum-2) - tmp(inum-2);

The last term should be "tmp(inum-3)."

-Dan

3. error('n is less than zero');

Maybe you mean disp('error(...etc...)') ?

I don't understand this bit:

if n < 2
f = n;
n = 2tmp(1) = 0;
f = n-1;

You assign the value n to f, and then 2 to n, and then n-1 to f, i.e. f=1! And what is f for anyway?

Expensive on code:
tmp(1) = 0;
tmp(2) = 1;
tmp(3) = 1;

Rather write:
tmp=[0 1 1];

Your structure may have to be:

if n < o
.
.
.
elseif n < 2
.
.
.
else
.
.
.
for
.
.
.
end
.
.
.
end

And also the error that topsquark pointed out.