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

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

 Accepted 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:

1 Comment

Thank you for your reply.I used to think numbered variables can be easier to understand and establish logical links. It seems that numbered variables just make my program more complicated. I will try to avoid that in the future.In addition, I think it's better to use 'wt' instead of 'rt' in this case.

Sign in to comment.

More Answers (0)

Asked:

on 16 Feb 2016

Edited:

on 16 Feb 2016

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!