Star
Star

Reputation: 2299

Vectorise a code to transform a vector into a matrix

I have a vector A of dimension Nx1 in MATLAB, e.g.

N = 5;
A = [1
     2
     3
     4
     5];

I want to construct a matrix B of dimension (N-1) x N such that:
for i=1,...,N, B(:,i) contains the rows 1,2,...,i-1,i+1,...,N of A.


In the example above,

B = [2 1 1 1 1
     3 3 2 2 2
     4 4 4 3 3
     5 5 5 5 4]

This code does what I want:

 B=zeros(N-1,N);
 for i=1:N
     if i>1 && i<N
         B(:,i)=[A(1:i-1); A(i+1:end)];
     elseif i==1
         B(:,i)=A(i+1:end);
     elseif i==N
         B(:,i)=A(1:i-1);
     end
 end

But I want to vectorise it. Any help?

Upvotes: 2

Views: 66

Answers (3)

gnovice
gnovice

Reputation: 125854

Here's a simple option:

[r, ~] = find(~eye(N));
B = reshape(A(r), N-1, N)

Upvotes: 4

Sardar Usama
Sardar Usama

Reputation: 19689

This is what nchoosek generates with a clockwise 90 degree rotation.

B = rot90(nchoosek(A,N-1),-1);   

Upvotes: 4

bla
bla

Reputation: 26069

per your example you can just delete every N+1 entry:

N=5;
a=repmat(1:N,1,N); % make an NxN long vector 
a(1:N+1:end)=[]; % delete every N+1 entry
B=reshape(a,N-1,[]) % reshape to N-1 x N matrix

Upvotes: 1

Related Questions