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

Vectorising a Matlab code to pick specific indices of a matrix

user3285148
1#
user3285148 Published in 2017-12-07 16:16:33Z

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
Leander Moesinger
2#
Leander Moesinger Reply to 2017-12-07 17:26:53Z

Extract the lower and upper triangular matrices of A. Then reassemble them with a "diagonal shift":

u = triu(A);
l = tril(A,-1);
B = padarray(u(1:end-1,:),[0 1],'pre') + padarray(l(2:end,:),[0 1],'post');
codeaviator
3#
codeaviator Reply to 2017-12-07 17:37:43Z

Another valid approach using logical indexing combined with tril and triu:

B = zeros(size(A'));
B(tril(true(size(B)))) = A(tril(true(size(A)), -1));
B(triu(true(size(B)), 1)) = A(triu(true(size(A))));

Result:

>> B

B =

     5     1     2     3     4
     9    10     6     7     8
    13    14    15    11    12
    17    18    19    20    16
You need to login account before you can post.

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

© 2016 Powered by mzan.com design MATCHINFO