Reputation: 11
I have a string of english alphabets and i want to swap first element with second and so on. I am using this code:
for a = 1:25;
b= 1;
k(a)= k(a+b);
end
I don't know whether its a right approach or not. Any help will be appreciated
Upvotes: 0
Views: 103
Reputation: 58
Swapping means first element must have the data of second element and second element must have data of first.
In your code you assigned first element the data of second element but you dind'nt do it the other way around.
i=0;
k=[1,2,3,4,5,6,7,8,9,10];
b=1;
for a= 1:5
t=k(a+i);
k(a+i)=k(a+b+i);
k(a+b+i)=t;
i=i+1;
end
Upvotes: -1
Reputation: 5821
This should work, assuming the array has an even length.
k = 'abcdefghijklmnop'
temp = k;
k(1:2:end) = temp(2:2:end);
k(2:2:end) = temp(1:2:end)
The result I get is
k =
badcfehgjilknmpo
EDIT: Luis Mendo mentioned an even better way:
k([1:2:end 2:2:end]) = k([2:2:end 1:2:end])
Upvotes: 3