MATLAB: Writing to file with condition

conditionextracting from matrixwriting to file

I have a matrix A 335×5 and I'm extracting 2nd and 3rd column from the matrix with the corresponding number. Currently, the program looks like this:
fileID = fopen('XY_Position.txt','w');
for i=1:nodes
fprintf(fileID,'%d,%.4f,%.4f\n',i,A(i,2),A(i,3));
end
fclose(fileID);
The output is:
1,355.3035,176.9755
2,353.8089,176.1707
3,352.1992,175.4808
4,350.7045,174.9059
5,344.1509,173.5262
6,338.0571,173.0663
7,332.8832,172.9513
8,330.2387,172.4914
etc
Now I need to include a condition where if, A(current row,4) Not Equal to A(next row,2), then extract elements A(current row,4) and A(current row,5). Please refer to the example below to understand the problem better.
For instance, we have a matrix:
22 305.2889 146.0469 306.5536 142.3677
23 306.5536 142.3677 301.6096 140.2981
24 301.6096 140.2981 299.0802 139.0333
25 299.0802 139.0333 297.0106 138.2285
26 518.2249 225.1505 507.1871 230.3245
27 507.1871 230.3245 505.0026 236.7631
28 505.0026 236.7631 503.5079 239.9825
As can be seen, the element A(current row, 4) is equal to A(next row,2), EXCEPT row 25 and 26.
The output is expected to be:
22,305.2889,146.0469
23,306.5536,142.3677
24,301.6096,140.2981
25,299.0802,139.0333
26,297.0106,138.2285
27,518.2249,225.1505
28,507.1871,230.3245
29,505.0026,236.7631
Please ask questions if problem is not clear enough. Your help is greatly appreciated.
Thank you.

Best Answer

I would just construct the matrix to be printed according to your rule, then write it in one go to file. If I understood correctly:
A = [22.0000 305.2889 146.0469 306.5536 142.3677
23.0000 306.5536 142.3677 301.6096 140.2981
24.0000 301.6096 140.2981 299.0802 139.0333
25.0000 299.0802 139.0333 297.0106 138.2285
26.0000 518.2249 225.1505 507.1871 230.3245
27.0000 507.1871 230.3245 505.0026 236.7631
28.0000 505.0026 236.7631 503.5079 239.9825];
B = sortrows([A(:, 1:3); A(A(1:end-1, 4) ~= A(2:end, 2), [1, 4, 5]) + [0.5, 0, 0]]); %requires R2016b or later
B(:, 1) = B(1, 1) + (0 : size(B, 1)-1);
csvwrite('XY_Position.txt', B);