Effacer les filtres
Effacer les filtres

how to swap some vector value?

6 vues (au cours des 30 derniers jours)
Mohammed Lamine Mekhalfia
Mohammed Lamine Mekhalfia le 24 Août 2021
Modifié(e) : Jan le 24 Août 2021
Dear all
I have the following vector
S=[1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 ...... ]
what I would like to do is to change 1 and 2 position to be after 10 then to 11 and 12 after 20 and etc.
so S will be like S= [3 4 5 6 7 8 9 10 1 2 13 14 15 16 17 18 19 20 11 12 ....]
I hope that the problem is well explained.
Thanks a lot in advance for your contribution

Réponses (3)

Star Strider
Star Strider le 24 Août 2021
Use the reshape and circshift functions:
S=[1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20]
S = 1×20
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
Sr = reshape(S,10,[])
Sr = 10×2
1 11 2 12 3 13 4 14 5 15 6 16 7 17 8 18 9 19 10 20
Src = circshift(Sr,-2,1)
Src = 10×2
3 13 4 14 5 15 6 16 7 17 8 18 9 19 10 20 1 11 2 12
Result = reshape(Src,1,[])
Result = 1×20
3 4 5 6 7 8 9 10 1 2 13 14 15 16 17 18 19 20 11 12
Note — ‘S’ must always have a length that is an integer multiple of 10 for this to work. An alternative to reshape if that is not the situation is the Signal Processing Toolbox buffer function, however the results of the last column might not be the desired result.
.

Wan Ji
Wan Ji le 24 Août 2021
Modifié(e) : Wan Ji le 24 Août 2021
A general answer is
S = 1:100; %
count = 1;
copyLength = 2; %
copyStep = 10; % copyStep>copyLength
while count<=numel(S)-copyLength
if(count==1)
copySeg = S(count:count+copyLength-1);
S(count:count+copyLength-1) = [];
count = count + copyStep - copyLength;
else
copyTemp = S(count:count+copyLength-1);
S(count:count+copyLength-1) = copySeg;
copySeg = copyTemp;
count = count + copyStep;
end
end
if(count-1<=numel(S))
nLen = count + copyLength -1 - numel(S);
S = [S, ones(1,nLen)];
S(count:count+copyLength-1) = copySeg;
end

Jan
Jan le 24 Août 2021
Modifié(e) : Jan le 24 Août 2021
% [EDITED] Now working if S has not a multiple of 10 elements:
S = 1:25;
a = 2; % Move 2 elements
b = 10; % in blocks of 10
v = 0:numel(S) - 1;
k = rem(v + a, b) + 1 + b * floor(v / b);
T = S(k(k <= numel(S)))
T = 1×23
3 4 5 6 7 8 9 10 1 2 13 14 15 16 17 18 19 20 11 12 23 24 25

Catégories

En savoir plus sur Logical dans Help Center et File Exchange

Produits


Version

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by