How to quickly fill in a matrix

Hi there,
Does anybody have a "fix" on how to make this function go faster? Essentially, I am trying to fill up the matrix Hpsi using the vector phi in a special way.
Thanks in advance, Andy.
T= 1000;
phi=[1:10];
Hpsi = speye(T);
phi=phi';
pl=length(phi);
for i=1:pl
Hpsi = Hpsi + sparse((i+1):T,1:(T-i),phi(i)*ones(1,T-i),T,T);
end

답변 (1개)

Christine Tobler
Christine Tobler 2015년 12월 17일

0 개 추천

Use spdiags:
spdiags(repmat(phi([end:-1:1 1])', T), -10:0, T, T)

댓글 수: 2

I find that your code is slower than what I proposed:
clear all;
clc;
T=1000;
phi=1:10;
pl=length(phi);
disp('my code:');
tic;
Hpsi = speye(T);
for i=1:pl
Hpsi = Hpsi + sparse((i+1):T,1:(T-i),phi(i)*ones(1,T-i),T,T);
end
toc;
disp('your code:');
tic;
Hpsi2 = spdiags(repmat(phi([end:-1:1 1])', T), -10:0, T, T);
toc
my code:
Elapsed time is 0.026569 seconds.
your code:
Elapsed time is 0.042326 seconds.
Sorry, I forgot an input:
spdiags(repmat(phi([end:-1:1 1])', T, 1), -10:0, T, T)

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Deep Learning Toolbox에 대해 자세히 알아보기

질문:

2015년 12월 15일

댓글:

2015년 12월 18일

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by