Move an element in a vector
Show older comments
I have a vector: [1 2 3 4 5]
And I need to do the following: put each element in the first position and stack the result together
The result would look like this: [1 2 3 4 5; 2 1 3 4 5; 3 1 2 4 5; 4 1 2 3 5; 5 1 2 3 4]
Is there any function/indexing (without loop) can do this?
Accepted Answer
More Answers (2)
cellfun()'s not got an explicit loop:
v = 1:5;
M = cell2mat(cellfun(@(x,idx)[x(idx) x(1:idx-1) x(idx+1:end)], ...
num2cell(repmat(v,numel(v),1),2), ...
num2cell((1:numel(v)).'), ...
'UniformOutput',false))
Or, probably better for small enough vectors, you can use perms(), keeping just the last row for each value in the first column:
idx = perms(1:numel(v));
M = v(flip(idx([diff(idx(:,1),1,1) ~= 0; true],:),1))
Or another way:
idx = repmat(1:numel(v)-1,numel(v),1);
is_upper = logical(triu(idx));
idx(is_upper) = idx(is_upper)+1;
M = v([(1:numel(v)).' idx])
Here is a simple for loop where I go down every row in the output array that we're going to create, placing the desired number in column 1, and all the rest of the numbers following that in the same row:
rowVector = [1 2 3 4 5];
columns = size(rowVector, 2);
output = zeros(columns, columns);
for row = 1 : length(rowVector)
% Put the number first, followed by all other numbers.
output(row, :) = [rowVector(row), setdiff(rowVector, row)];
end
% Echo result to the command window:
output
I compute what the other/remaining numbers are with the setdiff() function - a handy function to know about.
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!