MATLAB: How to write a circulation when save selected data into new matrix and then save new matrix into a text file

circulationdata extraction

I have a 140*1 matrix 'res' which consists of integers from 1 to 5.Now I am going to save all row numbers of integer into a new matrix label 1, and all row numbers of integer into a new matrix label 2. I used code below to get the corresponding data. However, if i don't know the length of original matrix 'res', how can i get the data using a circulation.(e.g label 'p'=find(res==p))
nClass = length(unique(res));
label1=find(res==1);
label2=find(res==2);
label3=find(res==3);
label4=find(res==4);
label5=find(res==5);
fid=fopen('1235.txt','wt');
fprintf(fid,'Docum ID: ');
fprintf(fid,'[%d] ',label1);
fprintf(fid,'\n\n');
fprintf(fid,'Docum ID: ');
fprintf(fid,'[%d] ',label2);
fprintf(fid,'\n\n');
fprintf(fid,'Docum ID: ');
fprintf(fid,'[%d] ',label3);
fprintf(fid,'\n\n');
fprintf(fid,'Docum ID: ');
fprintf(fid,'[%d] ',label4);
fprintf(fid,'\n\n');
fprintf(fid,'Docum ID: ');
fprintf(fid,'[%d] ',label5);
fprintf(fid,'\n\n');
fclose(fid);

Best Answer

The trick is do not create numbered variables:
fid = fopen('12345.txt','wt');
for k = 1:numel(res)
idx = find(res==k);
fprintf(fid,'%d ',idx);
fprintf(fid,'\n\n');
end
fclose(fid);
Although beginners think that numbered variables are a great idea, they actually just lead beginners to some very bad, slow buggy code: