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?

 採用された回答

Stephen23
Stephen23 2022 年 2 月 11 日

0 投票

V = 1:5;
N = numel(V);
A = repmat(1:N,N,1);
[~,X] = sort(tril(1+A,-1)+eye(N)+triu(A,1),2);
Z = V(X)
Z = 5×5
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

その他の回答 (2 件)

Voss
Voss 2022 年 2 月 11 日

1 投票

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))
M = 5×5
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
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))
M = 5×5
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
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])
M = 5×5
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
Image Analyst
Image Analyst 2022 年 2 月 11 日

0 投票

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
output = 5×5
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
I compute what the other/remaining numbers are with the setdiff() function - a handy function to know about.

カテゴリ

ヘルプ センター および File ExchangeCreating and Concatenating Matrices についてさらに検索

質問済み:

QP
2022 年 2 月 11 日

回答済み:

2022 年 2 月 11 日

Community Treasure Hunt

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

Start Hunting!

Translated by