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?
Asked
Active
Viewed 518 times
2

acbh
- 167
- 1
- 8
1 Answers
5
Here are some ways:
Concatenate and reshape:
x = [2,3,4,5,6,7]; y = reshape([x; -x], 1, []);
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;
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;

Community
- 1
- 1

Luis Mendo
- 110,752
- 13
- 76
- 147
-
Just beat me to it. :) – gnovice Feb 21 '17 at 19:26
-
Tried the first method. It gives me ``[2,3,4,5,6...-2,-3,-4,-5,-6]`` instead, but I need ``[2, -2, 3, -3..]`` though. – acbh Feb 21 '17 at 19:32
-
@gnovice 10 seconds! :-) – Luis Mendo Feb 21 '17 at 19:32
-
@acbh Did you check the updated answer? I initially had the `;` missing – Luis Mendo Feb 21 '17 at 19:32
-
@LuisMendo yup I used the updated answer, it didn't work :( – acbh Feb 21 '17 at 19:34
-
@acbh Paste this as is and check the result: `clear; x = [2,3,4,5,6,7]; y = reshape([x; -x],1,[])` – Luis Mendo Feb 21 '17 at 19:35
-
1@acbh: Is your vector a row or column vector? I'm guessing you are dealing with a column vector, but your question and this answer use row vectors as the input. – gnovice Feb 21 '17 at 19:37
-
@rahnema1 Why don't you post that as an answer and do the timing? ;-) Anyway, my feeling is that `kron` does more arithmetic operations and so it will be a little slower – Luis Mendo Feb 21 '17 at 20:06