acbh
acbh

Reputation: 167

Fastest way to construct an array with alternating positive and negative elements taken from a vector in matlab?

I have a vector that has values such as [2,3,4,5,6,7...], I would like to construct an array that repeat the values in the original vector but also has the negative of the original value right after it. So the resulting array from the given vector would be [2, -2, 3, -3, 4, -4...]. What would be the best way to do it in matlab?

Upvotes: 2

Views: 699

Answers (1)

Luis Mendo
Luis Mendo

Reputation: 112659

Here are some ways:

  1. Concatenate and reshape:

    x = [2,3,4,5,6,7];
    y = reshape([x; -x], 1, []);
    
  2. Preallocate y fast and then fill in the values:

    x = [2,3,4,5,6,7];
    y(numel(x)*2) = 0; % preallocate y
    y(1:2:end) = x;
    y(2:2:end) = -x;
    
  3. Preallocate and fill even-indexed values at the same time:

    x = [2,3,4,5,6,7];
    y(2:2:2*numel(x)) = -x;
    y(1:2:end) = x;
    

Upvotes: 5

Related Questions