2015-02-09 74 views
0

嗨,大家好,我想删除或终止含d> 8,这里是我的代码如何删除或MATLAB终止行

fileID = fopen('d.csv','w'); 


fprintf(fileID, ' a, b, d \n'); 
for a = -3:3 
    for b= -3:3 
      d = a^2 + b^2; 
      if d > 8 
       break; 
      else 
      fprintf(' %d, %d, %d, \n',a,b,d); 
      end 
    end 
end 

fclose(fileID); 

我用休息来删除行的行,突破仅适用于循环或while循环但它不起作用,输出显示标题,请帮助。

回答

2

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); 
+0

是啊你的语法工作,但很复杂,我认为它有限制,所以没有办法从我的代码中删除或终止行? – matlabnewbie 2015-02-09 07:09:54

+0

@matlabnewbie不能想到“局限性”,但是当我开始使用MATLAB时,我认为不容易遵循'bsxfun'。查看最后编辑的代码? – Divakar 2015-02-09 07:15:09

+0

谢谢:)你的天才 – matlabnewbie 2015-02-09 07:21:25