Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matlab code performance improvement

I have a matrix A (MxN) and need to create a matrix B (MxNxN) by using A such that B(:,1,1) = A(:,1), B(:,2,2) = A(:,2),..., B(:,N,N) = A(:,N). Currently I use,

B = zeros(size(A,1), size(A,2), size(A,2));
for i=1:size(B,3)
    B(:,i,i) = A(:,i);
end

Is it possible to use repmat or any other method to make this code run faster than it does now?

like image 475
suranga Avatar asked Mar 16 '26 11:03

suranga


1 Answers

It can be done using "partial" linear indexing on the last two dimensions of B, as follows:

[M, N] = size(A);
B = zeros(M, N, N);
B(:, 1:N+1:N^2) = A;
like image 75
Luis Mendo Avatar answered Mar 18 '26 01:03

Luis Mendo