Repeating a function n times and numbering output
조회 수: 7 (최근 30일)
이전 댓글 표시
I'm rather new to Matlab and I'm not really familiar with using any loops and couldn't find any appropriate solution so far.
I would like to create a loop which repeats n times (size if array) while accessing each row once. Then the output should be numbered so I can access the output individually.
I got this string array:
The code I have looks like following:
% Get size of array, not to be in loop
n = size(MatString,1);
% Access row
I1 = MatString(1,:);
% Create splitlines
I1 = splitlines(I1);
% Erase first row
I1(1,:) = [];
% --------------------------------------------------------
% Create separate Columns for MaterialIndexes
fid = fopen('outputIndex.txt','w');
fprintf(fid,'%s',MatString(1,1)); % would need to be MatString(n,1));
fclose(fid);
fid = fopen('outputIndex.txt');
stread = textscan(fid, '%f %.7f %.7f %.7f');
a=stread{1};
b=stread{2};
c=stread{3};
d=stread{4};
fid = fclose(fid);
% Replace MaterialIndex with effective colors
I1 = [a,b,c,d];
I1(isnan(I1))=999999999;
I1 = string(I1);
I1 = strrep(I1,'999999999','');
[ispresent, idx] = ismember(I1, ColorsIndexed(:,2));
I1(ispresent) = ColorsIndexed(idx(ispresent), 1);
% Replace MaterialIndex with colors in overall file
II = I1(:,1)+ I1(:,2) + I1(:,3)+ I1(:,4);
% Write output file of ColorIndex
fid = fopen('ColorIndex1.txt','w');
fprintf(fid,'%s',II);
fclose(fid);
I know it is may not the most elegant way, but it works like that.
Now I would like to repeat that n times with numbering the output vectors and the file, so the last one would be "I61" and "ColorIndex61.txt" in this case.
How would it be possible to loop this?
댓글 수: 3
Stephen23
2020년 5월 19일
Rik is correct: you should definitely avoid numbering variables, or putting any kind of meta-data into variable names. Accessing meta-data in variable names will make your code slow, complex, inefficient, and hard to debug.
The simplest would probably be to use a cell array, which can store data of different sizes in each cell:
This is also exactly what the MATLAB documentation recommends for importing data from multiple files:
답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!