0

Let's say I want to make a vector:

A = [4 8 16 32]

Is there any way to do this using the colon operator ? For example something like:

A = 4:(*2):32;
Daniel Widdis
  • 8,424
  • 13
  • 41
  • 63
Marko
  • 11
  • 1
  • 4
  • 5
    No, it cannot. The colon operator can only _add_ a fixed step to each value. But in this case you can transform your operation (multiplication) into a addition, and then convert back: `A = 2.^(2:5);` – Luis Mendo Apr 04 '19 at 14:24

1 Answers1

1

No, this is not possible in Matlab. You can use it like @Luis showed:

A = 2.^(2:5);

Or if you want to do this with a different function in the future:

A = [];
for n = 2:5
    A = [A n^2];
end

By changing the limits of the for loop and the n^2 part to your desired values, you can do it however you like.

Hope this helps.

byetisener
  • 310
  • 2
  • 11
  • 3
    Extending an array with `A=[A,n]` is highly inefficient. It is [much, much faster](https://stackoverflow.com/a/48990695/7328782) to do `A(end+1)=n`. However, if possible, one should always [preallocate](https://www.mathworks.com/help/matlab/matlab_prog/preallocating-arrays.html) instead of repeatedly extending the array. – Cris Luengo Apr 04 '19 at 17:29