I am trying to optimise the computation time of my code (for the second time after a first optimisation that gives very good results). Currently, this code is very time-consuming depending on the size of the data (i.e. sometimes very big matrices). So if anyone has some ideas to help me to optimize this code, I will be very grateful!
matrice1=0+(20-0).*rand(500,5);
matrice2=datasample(matrice1,100);
[n1,~]=size(matrice1);
[n2,p2]=size(matrice2);
% Pre-calculate replicated B and the indices to be modified at each iteration
B_rep=repmat(matrice2,[1 1 n2]);
B_idx=bsxfun(@plus,((0:p2-1)*n2+1)',(0:n2-1)*(n2*p2+1));
B=mean(B_rep,1);
out=zeros(n1,n2); % initialize output array
for i=1:n1
B_rep(B_idx)=repmat(matrice1(i,:)',1,n2);
B_meanB=bsxfun(@minus,B_rep,B); % B minus mean values of B
A_B_meanB=matrice2'-reshape(B,p2,[]); % A minus B_meanB
for j=1:n2
[~,R]=qr(B_meanB(:,:,j),0);
out(i,j)=sum((R'\A_B_meanB(:,j)).^2)*(n2-1);
end
end