Create a matrix A = [4 ... 128] in Octave language

Viewed 55

Can you help to know how to create a matrix in Octave using a shortened way?

I need to have (matrix) A = [4, 8, 16, 32, 64, 128]; Want to use something like A = [4: *2 : 128] (meaning start = 4, step = *2 : finish = 128), but this doesn't work in Octave.

The same needs to be done to matrix B = [1 4 9 16 25 36], where step is 3 at the beginning and is increasing by 2 on the next step.

Any ideas?

2 Answers

With the colon operator you can only do steps of the same size. But notice that your matrix

A = [4, 8, 16, 32, 64, 128];

has the structure [2^2, 2^3, 2^4, ..., 2^7], so you can make use of broadcasting and define it as

A = 2.^[2,3,4,5,6,7];

or simply

A = 2.^(2:7);

You can use a loop for that task. You just need to write a consistent rule in the statments of your loop. A possible way to do that is the following:

  start=1;
  finish=36;

  matrix(1)=start; i=2; last_term=start; %inicializations needed for the loop start
  while last_term < finish
    matrix(i)=matrix(i-1)+(1+2*(i-1)); %here you define your rule
    last_term=matrix(i);
    i=i+1;
  endwhile
  matrix %your output is printed in the console
Related