Home Vectorising a Matlab code to pick specific indices of a matrix
Reply: 0

Vectorising a Matlab code to pick specific indices of a matrix

user1401
1#
user1401 Published in July 16, 2018, 2:44 am

I have a matrix A in Matlab of dimension Nx(N-1), e.g.

N=5;
A=[1  2  3  4; 
   5  6  7  8;
   9  10 11 12;
   13 14 15 16;
   17 18 19 20];

I want to rearrange the elements of A in a certain way. Specifically I want to create a matrix B of dimension (N-1)xN such that:

for i=1,...,N,

B(:,i) collects

1) the first i-1 elements of the i-1th column of A and

2) the last N-i elements of the ith column of A.

Notice that for i=1 the i-1th column of A does not exist and therefore 1) is skipped; similarly, for i=N theith column of A does not exist and therefore 2) is skipped.


In the example above

B=[5  1  2  3  4
   9  10 6  7  8
   13 14 15 11 12
   17 18 19 20 16];

This code does what I want. I am asking your help to vectorise it in an efficient way.

B=zeros(N-1,N);
for i=1:N
    if i>1 && i<N
    step1=A(1:i-1,i-1);
    step2=A(i+1:N,i);
    B(:,i)=[step1;step2];
    elseif i==1
    B(:,i)=A(i+1:N,i);     
    elseif i==N
    B(:,i)=A(1:i-1,i-1);
    end
end
You need to login account before you can post.

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

© 2016 Powered by mzan.com design MATCHINFO