这是我的实际代码:
Lr = linspace(100,300,10);
vi = linspace(10,30,10);
vf = linspace(10,30,10);
b = linspace(0.5,1.2,10);
h = linspace(0.3,0.8,10);
Rc = [1000, 1500, 2000, 2500, 3000, 3500;
29, 22.4, 17.3, 13.4, 10.4, 8];
rti = randi(5, 10, 1, 10, 10, 10, 10);
for kk = 1:rows(Lr)
for jj = 1:length(vi)
for ll = 1:length(vf)
for mm = 1:length(b)
for nn = 1:length(h)
ratt(kk,1,jj,ll,mm,nn) = Rc(2,rti(kk,1,jj,ll,mm,nn));
endfor
endfor
endfor
endfor
endfor
在此示例中,所有向量的长度均为10,但在实际代码中,它们的长度可以为1至100。 如何删除所有这些循环?
答案 0 :(得分:0)
ratt
到Rc
作为一维数组。ratt
重塑为6D数组。代码:
ratt = Rc(2, rti(1:rows(Lr), 1, 1:length(vi), 1:length(vf), 1:length(b), 1:length(h)));
ratt = reshape(ratt, [rows(Lr), 1, length(vi), length(vf), length(b), length(h)]);
测试:为了测试矢量化和非矢量化代码的等同性和速度,我编写了以下代码:
Lr = linspace(100,300,10);
vi = linspace(10,30,10);
vf = linspace(10,30,10);
b = linspace(0.5,1.2,10);
h = linspace(0.3,0.8,10);
Rc = [1000, 1500, 2000, 2500, 3000, 3500;
29, 22.4, 17.3, 13.4, 10.4, 8];
rti = randi(5, 10, 1, 10, 10, 10, 10);
disp('Non-vectorized:')
tic
for kk = 1:rows(Lr)
for jj = 1:length(vi)
for ll = 1:length(vf)
for mm = 1:length(b)
for nn = 1:length(h)
ratt(kk,1,jj,ll,mm,nn) = Rc(2,rti(kk,1,jj,ll,mm,nn));
endfor
endfor
endfor
endfor
endfor
toc
disp('')
disp('Vectorized:')
tic
ratt1 = Rc(2, rti(1:rows(Lr), 1, 1:length(vi), 1:length(vf), 1:length(b), 1:length(h)));
ratt1 = reshape(ratt1, [rows(Lr), 1, length(vi), length(vf), length(b), length(h)]);
toc
disp('')
if(isequal(ratt,ratt1))
disp('ratt is equal to ratt1!')
else
disp('ratt is not equal to ratt1!')
endif
输出:
Non-vectorized:
Elapsed time is 0.16697 seconds.
Vectorized:
Elapsed time is 0.000309944 seconds.
ratt is equal to ratt1!