Manahil
Manahil

Reputation: 265

Sequence in MATLAB

Write a single MATLAB expression to generate a vector that contains first 100 terms of the following sequence: 2, -4, 8, -16, 32, …

My attempt :

n = -1 
for i = 1:100 
    n = n * 2 
    disp(n)
end

The problem is that all values of n is not displayed in a single (1 x 100) vector. Neither the alternating positive and negative terms are shown. How to do that ?

Upvotes: 1

Views: 1629

Answers (2)

Autonomous
Autonomous

Reputation: 9075

Though there are better methods, as mentioned in the answer by @lakesh. I will point out the mistakes in your code.

  1. By typing n = n * 2, how can it become a vector?
  2. By doing n=n * 2, you are going to generate -2, -4, -8, -16, ...

Therefore, the correct code should be:

n = -1 
for i = 2:101 % 1 extra term since first term has to be discarded later 
    n(i) = -n(i-1) * 2;
    disp(n)
end

You can discard first element of n, to get the exact series you want.

n(end)=[];

Upvotes: 2

lakshmen
lakshmen

Reputation: 29064

You are having a geometric series where r = -2.

To produce 2, -4, 8, -16, 32, type this:

>>-(-2).^[1:5]

 2, -4, 8, -16, 32

You can change the value of 5 accordingly.

Upvotes: 4

Related Questions