Circularly exclude elements.

조회 수: 1 (최근 30일)
Abhijit Chowdhary
Abhijit Chowdhary 2019년 4월 7일
댓글: Abhijit Chowdhary 2019년 4월 8일
Hello all,
I'm trying to compactly write a line of code for a interesting program I'm working on. Fixing , suppose we have the following code:
x = 1:n;
non_adj = zeros(n,n-2);
for k=1:n
non_adj(k,:) = []; %in here comes the confusion
end
In non_adj(k,:) I would like to fill in x without the elements k-1 and k+1. However, these elements are regarded circularily, i.e. if I have , then I want (order of elements irrelevant). I know I can do this with if statements handling the cases, but I was wondering if you all had a nicer way to one liner the construction.
I attempted the following construction
non_adj(k,:) = [k, k+2:mod(k-3,n)+1, mod(k+1,n)+1:k-2];
However this fails, for example, where . The above would construct the array , where in fact I wanted .
Do you have any ideas? If it helps, the context is that I'm trying to construct a vertex set minus the neighbors of vertex k, which happen to be (circularily shifted for ).
EDIT: I've realized I could use set differencing, i.e.: (however, you still might come up with better ideas).
non_adj(k,:) = setdiff([1:n], 1 + [mod(k-2,n) mod(k,n)]);
  댓글 수: 2
madhan ravi
madhan ravi 2019년 4월 7일
explicitly state your desired output
Abhijit Chowdhary
Abhijit Chowdhary 2019년 4월 7일
편집: Abhijit Chowdhary 2019년 4월 7일
If , then I want . If , then I want . Otherwise I want , and I'm hoping for a one-line to cover these scenarios.

댓글을 달려면 로그인하십시오.

채택된 답변

David Goodmanson
David Goodmanson 2019년 4월 7일
Hi Abhijit,
try
x = 1:n;
x(mod([k-1 k+1]-1,n)+1) = []
  댓글 수: 3
David Goodmanson
David Goodmanson 2019년 4월 8일
편집: David Goodmanson 2019년 4월 8일
Hi Abhijit,
I thought that for a given k, you wanted to keep k, exclude k-1 and k+1 and keep the rest of them, doing so in a circular fashion. Could you give me a quick example of where the code above doesn't work? I am having trouble finding one (n.b. both lines of code have to be run for each new value of k).
Abhijit Chowdhary
Abhijit Chowdhary 2019년 4월 8일
Ah, no it's my fault, you're right. I did not realize that x was being changed when you do this, and blindly continued to test on it. Yes, this indeed works, thanks!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

제품


릴리스

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by