Effacer les filtres
Effacer les filtres

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

3 vues (au cours des 30 derniers jours)
marianne
marianne le 6 Mar 2023
Commenté : marianne le 7 Mar 2023
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]

Réponse acceptée

Stephen23
Stephen23 le 6 Mar 2023
Modifié(e) : Stephen23 le 6 Mar 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

Plus de réponses (1)

Sarvesh Kale
Sarvesh Kale le 6 Mar 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

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Produits


Version

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by