Repeating a function n times and numbering output

조회 수: 7 (최근 30일)
Daniel Rohrer
Daniel Rohrer 2020년 5월 18일
댓글: Stephen23 2020년 5월 19일
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
Daniel Rohrer
Daniel Rohrer 2020년 5월 19일
Ok, so how can I access all rows with indexing? And store the results in I(k) arrays? The cells of the MatString array are not all the same size, so the outputs I(k) differ from 100:1 to 5:1.
fid = fopen('outputIndex.txt','w');
fprintf(fid,'%s',MatString(1,1)); % would need to be MatString(n,1));
fclose(fid);
Here I access the first row, and I need to repeat that n times and store it in a separate array as I need to compare it with "ColorsIndexed"
Stephen23
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 CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품


릴리스

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by