如何在 matlab 中删除或终止行

How to delete or terminate rows in matlab

大家好,我想删除或终止包含 d>8 的行,这是我的代码

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

我用break删除行,break只适用于循环或while循环,但它在我的中不起作用,输出显示的是标题,请帮助。

一个vectorized approach to get things done faster!? The code listed next could be one such approach that uses a great tool for vectorization - bsxfun and then writes to output file with another fast I/O writing tool - 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

新手for循环代码-

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