How to rearrange a row vector into a pair wise column vector?

4 visualizaciones (últimos 30 días)
Hello, I have a row vector with a series of 21 values, for example from 1 to 21
v = [1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21]
and I need to rearrange it so it becomes a 20x2 vector like the one below, with the second value of the pair repeating in each new row.
I am sure there is a nice loop to do this, but I can't find a solution. Thank you
v2 = [1 2
2 3
3 4
4 5
5 6
...
20 21]

Respuesta aceptada

Stephen23
Stephen23 el 6 de Mzo. de 2023
Editada: Stephen23 el 6 de Mzo. de 2023
"I am sure there is a nice loop to do this, but I can't find a solution."
This is MATLAB, so loops are not required:
v = 1:21
v = 1×21
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
m = [v(1:end-1);v(2:end)].'
m = 20×2
1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 10 10 11

Más respuestas (1)

Sarvesh Kale
Sarvesh Kale el 6 de Mzo. de 2023
See if the following code snippet can help you
v = [1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21];
v2= [] ;
for i=1:2
v2(:,i) = v(1+i-1:20+i-1)';
end
disp(v2)
I hope this helps you, please accept the answer if it does
Thank you

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Productos


Versión

R2020a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by