MATLAB: Nested FOR loops and creating text file (3d-layers) too slow.

MATLABnested for loopprogrammingslow

Hello everyone,
I am pretty new with Matlab. I am facing a problem concering nested for-loops and creating a text file. It is too slow. The text file contains data for 3d-layers.
If the number of layers and rows and columns in each layer are too big, it takes lots of hours to execute the code.
If anyone here can help me regarding to optimize my code or telling me an alternate to solve this problem, it would be very helpful.
Thank you very much.
clc
clear all
b=100;
l=150;
d=0.1;
dn=1.0;
nnR=b/dn+1;
nnC=l/dn+1;
nL=d/0.1+1;
R=1;
C=1;
L=0;
x=0;
y=0;
z=0;
space=' ';
add=0;
nline=sprintf('Start\ntextfileindex\n$ nod row column layer \n');
% fileID=fopen('node.txt','w');
% fprintf(fileID,'%s', q);
for b = 1:nL
for i = 1:nnR
dummieR=R
for i = 1:nnC
abc=b;
abc=num2str(abc);
if b<10
abc=strcat('0',abc)
else
abc=b;
end
dummieC=C
numC=num2str(dummieC)
dummiex=x
dummiey=y
dummiez=z
numz = sprintf('%.4f',dummiez)
numx = sprintf('%.4f',dummiex)
numy = sprintf('%.4f',dummiey)
% numx = sprintf('%.4f',dummiex)

if C<100 && C>9
numC=strcat('0',numC)
end
if C<10
numC=strcat('00',numC)
end
numR=num2str(dummieR)
if R<100 && R>9
numR=strcat('0',numR)
end
if R<10
numR=strcat('00',numR)
end
% dummiex=x
% numx = sprintf('%.4f',dummiex)
% numx=num2str(dummiex)
if dummiex<100 && dummiex>9.9999
def= "\n"+abc+numR+numC+" "+numx
elseif dummiex<10
def= "\n"+abc+numR+numC+" "+numx
else
def= "\n"+abc+numR+numC+" "+numx
end
if dummiey<100 && dummiey>9.9999
def= def+" "+numy
elseif dummiey<10
def= def+" "+numy
else
def= def+" "+numy
end
if nL<10
def= def+" "+numz
else
def= def+" "+numz
end
C=C+1;
nline= strcat(nline,def)
nline= sprintf(nline)
x=x+dn;
end
R=R+1;
C=1;
y=y+dn;
x=0;
end
z=z+0.1;
x=0;
y=0;
C=1;
R=1;
end
nline=sprintf(nline+ "\n" + "END")
fileID=fopen('textfilem.txt','wt');
fprintf(fileID, nline);

Best Answer

So, as suspected, just generate the data to print and use the desired formatting string:
% generate some sample data...
A=1001000+[1:11];
B=0:5:50;
C=[A.' B.' zeros(numel(A),2)];
% define the desired format for output file...
fmt=['%08d' repmat('%12.4f',1,3) '\n'];
% Illustrate what will get to command line...
>> fprintf(1,fmt,C.')
01001001 0.0000 0.0000 0.0000
01001002 5.0000 0.0000 0.0000
01001003 10.0000 0.0000 0.0000
01001004 15.0000 0.0000 0.0000
01001005 20.0000 0.0000 0.0000
01001006 25.0000 0.0000 0.0000
01001007 30.0000 0.0000 0.0000
01001008 35.0000 0.0000 0.0000
01001009 40.0000 0.0000 0.0000
01001010 45.0000 0.0000 0.0000
01001011 50.0000 0.0000 0.0000
>>
NB1: Internal Matlab storage order is column major so must transpose C to output by row for sequential file.
NB2: The first column is possible to be written as part of formatting statement as well if the values are just 1:N. Include the literal string '0100' in the format string as '0100%05d' to handle i from 1:99999