Home Vectorise a code to transform a vector into a matrix
Reply: 3

Vectorise a code to transform a vector into a matrix

user3285148
1#
user3285148 Published in 2017-12-07 17:20:51Z

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?

Sardar Usama
2#
Sardar Usama Reply to 2017-12-07 18:09:55Z

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

B = rot90(nchoosek(A,N-1),-1);   
bla
3#
bla Reply to 2017-12-07 17:35:12Z

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
gnovice
4#
gnovice Reply to 2017-12-07 18:27:25Z

Here's a simple option:

[r, ~] = find(~eye(N));
B = reshape(A(r), N-1, N)
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.370857 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO