※ 引述《ericrobin ()》之铭言:
: 2. 另一个关于循环, 程式某段落长这样, 其中 Ht 为 (M*t X M) 的矩阵
: stemp6 = zeros(M,1);
: stemp5 = [];
: stemp7 = [];
: for i = 1:t
: stemp8 = Ht((i-1)*M+1:i*M,:);
: stemp7a = [];
: ic = 1;
: for j = 1:M
: stemp7a = [stemp7a ; stemp8(j,1:ic)'];
: ic = ic+1;
: stemp6(j,1) = sqrt(Ht((i-1)*M+j,j));
: end
: stemp5 = [stemp5 ; stemp6'];
: stemp7 = [stemp7 ; stemp7a'];
: end
: 这种写法会让矩阵维度不断改变,
: 想请问该如何改写才有效率呢?
直接向量化,就好了,这里用num2cell + cellfun也可以,但是我认为不会快多少
浪费一点内存多复制几次M by M的矩阵应该还OK
clear all
M = 400;
t = 100;
Ht = rand(M*t, M);
tic
stemp6 = zeros(M,1);
stemp5 = [];
stemp7 = [];
for i = 1:t
stemp8 = Ht((i-1)*M+1:i*M,:);
stemp7a = [];
ic = 1;
for j = 1:M
stemp7a = [stemp7a ; stemp8(j,1:ic)'];
ic = ic+1;
stemp6(j,1) = sqrt(Ht((i-1)*M+j,j));
end
stemp5 = [stemp5 ; stemp6'];
stemp7 = [stemp7 ; stemp7a'];
end
toc
% Elapsed time is 2.250143 seconds.
tic
Ht_2 = Ht';
stemp7_2 = reshape(Ht_2(repmat(triu(ones(M,M)), 1, t) > 0), [], t)';
stemp5_2 = reshape(sqrt(Ht_2(repmat(eye(M), 1, t) > 0)), [], t)';
toc
% Elapsed time is 0.213150 seconds.
tic
Ht_3 = Ht';
stemp7_3 = reshape(Ht_3(repmat(triu(true(M,M)), 1, t)), [], t)';
stemp5_3 = reshape(sqrt(Ht_3(repmat(speye(M), 1, t) > 0)), [], t)';
toc
% Elapsed time is 0.125851 seconds.
isequal(stemp7, stemp7_2) % true
isequal(stemp5, stemp5_2) % true