MATLAB: Rotate vector in row

2-optdepotsrotate

Hi, i have an array
n= [1,19,15,18,21,10,16,2,7,3,17,6,1;
1,14,20,8,4,13,9,5,1,0,0,0,0;
1,11,12,1,0,0,0,0,0,0,0,0,0];
What i need to do is to randomly choose 2 elements of each row (but not the ones and the zeros) and rotate the vector in between them .
For example new_n= [ 1,19,15,17,3,7,2,16,10,21,18,6,1;
1,14,13,4,8,20,9,5,1,0,0,0,0;
1,12,11,1,0,0,0,0,0,0,0,0,0]
If it is possible i would like to be able to do it for any array i might have. (the thing is that 1-etc-1 in each row are non equal paths that start at depot 1 and end at it after they go through the other nodes, so i want the rearrangement to happen between the depots)

Best Answer

This may solve your problem:
rng(42)
n= [1,19,15,18,21,10,16,2,7,3,17,6,1;
1,14,20,8,4,13,9,5,1,0,0,0,0;
1,11,12,1,0,0,0,0,0,0,0,0,0];
nrev = n;
for idx=1:size(n,1)
% Get the position of the initial 0
Ncolums = find(n(idx,:)==0);
if isempty(Ncolums)
Ncolums = size(n,2);
else
Ncolums = Ncolums(1)-1;
end
Ncolums = Ncolums-2; % Remove first and last 1
% Get a random index permutation between valid index
Index = randperm(Ncolums)+1; % Add offset so it starts by two
Index = sort(Index(1:2));
% Invert row
nrev(idx,Index(1):Index(2)) = n(idx,Index(2):-1:Index(1));
end
nrev
nrev =
1 19 15 18 21 10 16 6 17 3 7 2 1
1 14 20 8 13 4 9 5 1 0 0 0 0
1 12 11 1 0 0 0 0 0 0 0 0 0