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

3 Ansichten (letzte 30 Tage)
marianne
marianne am 6 Mär. 2023
Kommentiert: marianne am 7 Mär. 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]

Akzeptierte Antwort

Stephen23
Stephen23 am 6 Mär. 2023
Bearbeitet: Stephen23 am 6 Mär. 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

Weitere Antworten (1)

Sarvesh Kale
Sarvesh Kale am 6 Mär. 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

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Produkte


Version

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by