vectorized
怎麼樣讓事情做得更快!下面列出的代碼可能是用來量化一個偉大的工具這樣一個方法 - bsxfun
,然後寫入到輸出文件與另一個快速I/O書寫工具 - dlmwrite
-
file = 'results.txt'; %//'# Path to output text or csv file
offset = 3; %// offset factor used inside the loops
comp = 8; %// value to be compared against for D
%// Find all possible d values
dvals = bsxfun(@plus,[-offset:offset]'.^2,[-offset:offset].^2) %//'
%// Find a and b values satisfying the comparison criteria
[avals,bvals] = ind2sub(size(dvals),find(dvals <= comp))
%// Write the values to the output file with dlmwrite
dlmwrite(file,' a, b, d ','')
dlmwrite(file,[avals(:)-offset-1 bvals(:)-offset-1 dvals(dvals<=comp)],'-append')
驗證結果 -
>> type(file)
a, b, d
-2,-2,8
-1,-2,5
0,-2,4
1,-2,5
2,-2,8
-2,-1,5
-1,-1,2
0,-1,1
1,-1,2
2,-1,5
-2,0,4
-1,0,1
0,0,0
1,0,1
2,0,4
-2,1,5
-1,1,2
0,1,1
1,1,2
2,1,5
-2,2,8
-1,2,5
0,2,4
1,2,5
2,2,8
對於循環代碼的新手 -
fprintf(fileID, ' a, b, d \n');
for a = -3:3
for b= -3:3
d = a^2 + b^2;
if d <= 8
fprintf(fileID,' %d, %d, %d, \n',a,b,d);
end
end
end
fclose(fileID);
是啊你的語法工作,但很複雜,我認爲它有限制,所以沒有辦法從我的代碼中刪除或終止行? – matlabnewbie 2015-02-09 07:09:54
@matlabnewbie不能想到「侷限性」,但是當我開始使用MATLAB時,我認爲不容易遵循'bsxfun'。查看最後編輯的代碼? – Divakar 2015-02-09 07:15:09
謝謝:)你的天才 – matlabnewbie 2015-02-09 07:21:25