Matlab函数性能 - 循环太多 [英] Matlab Function Performance - Too many loops
问题描述
我必须在很多行中写入多个信息的txt文件。结果是一个文件,如:
I have to write in a txt file several informations in a LOT of rows. The result is a file like:
result.txt:
RED;12;7;0;2;1;4;7;0.0140
RED;12;7;0;2;2;9;7;0.1484
RED;12;7;0;2;3;7;4;0.1787
RED;12;7;0;2;4;2;6;0.7891
RED;12;7;0;2;5;9;6;0.1160
RED;12;7;0;2;6;9;1;0.9893
...
通过下面的代码(缩小尺寸):
Which is build by the code below (with some reduced dimensions):
/* the variables 'str1', 'num1', 'day', 'vect1', 'vect2' and 'MD' are inputs of this function
/* str1 is a string 1x1
/* num1 is a integer 1x1
/* day is a vector 10x1
/* vect1 is a vector 7x1
/* vect2 is a vector 180x1
/* MD is a 4D matrix (7x180x10x15)*/
fid = fopen(path_result, 'Wt');
for i1 = 1:15
for i2 = 1:10
for i3 = 1:7
for i4= 1:180
/* print all the values */
fprintf(fid,'%s%s%d%s%d%s%d%s%d%s%d%s%d%s%d%s%.4f \n',...
str1,';',num1,';',i1,';',0,';',2,';',...
day(i2,1),';',vect1(i3),';',...
vect2(i4),';',MD(i3,i4,i2,i1));
end
end
end
end
I在这里看到了一些向量化(stackoverflow后),但我不认为可以在这里申请。有任何想法吗?
预先感谢
I saw some vectorization in here (stackoverflow post), but I don't think it's possible to apply in here. Any ideas?
Thanks in advance
推荐答案
可应用于任何情况的第一个优化是生成一个格式字符串,称它为 fmt
:
A first optimization which can be applied to any situation is to generate a format string, let's call it fmt
:
fmt = sprintf('%s;%d;%%d;%d;%d;%%d;%%d;%%d;%%.4f \\n',str1,num1,0,2)
fmt =
RED;4;%d;0;2;%d;%d;%d;%.4f \n
之后循环中的代码变成:
After which the code inside the loops become:
x = sprintf(fmt, i1, day(i2,1), vect1(i3), vect2(i4), MD(i3,i4,i2,i1));
现在,一个完全的矢量化一个数量级的加速,在我的设置~10.8x从9.61到0.89秒。
Now, a fully vectorized solution, which trades off on RAM but achieves an order of magnitude speedup, on my setup ~10.8x from 9.61 to 0.89 seconds.
tic
[a,b,c,d] = ndgrid(vect2,vect1,day,1:15);
out = sprintf(fmt, [d(:), c(:), b(:), a(:), reshape(permute(MD,[2,1,3,4]),[],1)]');
toc
这篇关于Matlab函数性能 - 循环太多的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!