Hi, suppose N is a scalar, and c is a numerical vector with unique elements that are a subset of 1:N, i.e. its size is smaller or equal to N. For example, N=4, and c=[1 2 4]'; Then, is there a more elegant way to achieve this?
cc = [];
for j = 1:N
if ismember(j,c)
cc = [cc; N*(j-1)+c];
end
end
Thanks!

댓글 수: 2

Stephen23
Stephen23 2017년 6월 23일
What do you expect the output cc to be?
Christian
Christian 2017년 6월 23일
If N=4, and c=[1 2 4]'; then cc is going to be [1 2 4 5 6 8 13 14 16]'.

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

 채택된 답변

Andrei Bobrov
Andrei Bobrov 2017년 6월 23일
편집: Andrei Bobrov 2017년 6월 23일

1 개 추천

[Fixed]
N = 15;
c = randperm(N,4);
c1 = sort(c(:));
cc = reshape(bsxfun(@plus,N*(c1 - 1),c1')',[],1);
or
oc = ones(numel(c1),1);
cc = N*(kron(c1,oc) - 1) + kron(oc,c1);
or
c = c(:);
nn = numel(c);
cc = N*(repelem(c,nn) - 1) + repmat(c,nn,1);

댓글 수: 6

Christian
Christian 2017년 6월 23일
Thanks, but cc should be a column vector of size length(c)^2. You seem to be getting a matrix, and the elements are not right either. c is a column vector.
Vector?
>> N=4;
c=[1 2 4];
cc = [];
for j = 1:N
if ismember(j,c)
cc = [cc; N*(j-1)+c];
end
end
>> cc
cc =
1 2 4
5 6 8
13 14 16
>>
Christian
Christian 2017년 6월 23일
편집: Christian 2017년 6월 23일
c is a column vector, not a row vector. Then, cc will also be a column vector. And c is sorted to begin with.
Andrei Bobrov
Andrei Bobrov 2017년 6월 23일
I'm fixed my answer.
Stephen23
Stephen23 2017년 6월 23일
@Christian: With the data you have shown us cc will definitely be a matrix. If c is a column vector then you should specify this in your question.
Christian
Christian 2017년 6월 23일
I think that gives the right result. I wish it was more readable / elegant.

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

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

질문:

2017년 6월 23일

편집:

2017년 6월 23일

Community Treasure Hunt

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

Start Hunting!

Translated by