How to select an array without element i

14 ビュー (過去 30 日間)
Romy Schipper
Romy Schipper 2017 年 6 月 7 日
コメント済み: Stephen23 2017 年 6 月 7 日
I want to select an array of a matrix without element i
so if
a =
1
4
7
11
n = 4
V = zeros(3,n)
i want to be able to select
a(:-i)
pseudo code:
for i = 1:n
V(:,1) = a(:-i) %so everthing from a except from element on i'th place
end
And then I want the output to be
V =
4 1 1 1
7 7 4 4
11 11 11 7
I hope someone can help me! sorry for bad englisch
  1 件のコメント
Stephen23
Stephen23 2017 年 6 月 7 日
Question for those who enjoy challenges: is there a solution which does not remove elements from a larger array? That would mean no setdiff, eye, etc, and extra points if it does not use a loop :)

サインインしてコメントする。

採用された回答

Stephen23
Stephen23 2017 年 6 月 7 日
編集済み: Stephen23 2017 年 6 月 7 日
>> a = [1;4;7;11];
>> n = numel(a);
>> M = reshape(a(1+mod(setdiff(1:n*n,1:n+1:n*n)-1,n)),n-1,n)
M =
4 1 1 1
7 7 4 4
11 11 11 7

その他の回答 (3 件)

Jan
Jan 2017 年 6 月 7 日
編集済み: Jan 2017 年 6 月 7 日
While I prefer Stephen's or Andrei's vectorized solutions for the productive use, the actual question can be solved in a loop also:
a = [1; 4; 7; 11];
n = 4;
V = zeros(3, n);
for k = 1:n
V(:, k) = a(setdiff(1:n, k));
end
Or:
index = true(1, 4);
for k = 1:n
index(k) = false;
V(:, k) = a(index);
index(k) = true;
end
Or:
V = repmat(a, 1, n);
V(1:n+1:end) = [];
V = reshape(V, n-1, n);
Or:
[index, dummy] = find(~eye(n));
V = reshape(a(index), [], n)

H ZETT M
H ZETT M 2017 年 6 月 7 日
This is not pretty, but it works:
a =[1;4;7;11]
n = 4
V = zeros(3,n)
for i=1:n
V(:,i)=a([1:i-1 i+1:end])';
end

Andrei Bobrov
Andrei Bobrov 2017 年 6 月 7 日
編集済み: Andrei Bobrov 2017 年 6 月 7 日
n = numel(a);
V = reshape(nonzeros(repmat(a,1,n).*~eye(n)),[],n)

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by