I want to put numbers from 1 to 8 after the file name using 'for loop' and save this file name as a variable.
43 次查看(过去 30 天)
显示 更早的评论
I want to put numbers from 1 to 8 after the file name using 'for loop' and save this file name as a variable.
fn_1 = file name1.txt
fn_2 = file name2.txt
fn_3 = file name3.txt
...
fn_8 = file name8.txt
In this way, I want to store each of them in a variable.
What should I do?
C:\Users\file name.txt The file name.txt file exists in that path.
This is the code I made by me.
for num = 1 : 8
disp(sprintf('C:\\Users\\file name%d.txt'));
end
I've only printed out file names (1 to 8).
0 个评论
采纳的回答
Stephen23
2022-3-2
编辑:Stephen23
2022-3-2
"In this way, I want to store each of them in a variable."
That would be a very inefficient use of MATLAB. MATLAB is designed to use arrays. You should use arrays:
P = 'C:\Users';
V = 1:8;
T = compose("file name%d.txt",V(:))
T = fullfile(P,T)
If you want to import that file data, use something like this:
N = numel(V);
C = cell(1,N);
for k = 1:N
F = sprintf('file name%d.txt',V(k));
C{k} = readmatrix(fullfile(P,F)); % or READTABLE, etc.
end
3 个评论
Stephen23
2022-3-3
"I understand that V(:) stores T as a column vector"
(:) indexing returns a column vector, which is then provided as the 2nd input to COMPOSE.
"but I wonder why the numbers from 1 to 8 are included in the %d part."
COMPOSE uses the format string (1st argument) to convert the other inputs into the output text.
"I'm confused because I only know that things like %d%f specify text format. Can you explain it?"
%d is also used here to specify the text format: it tells COMPOSE how we want the input numbers to look like in the output text. The rest of the format string is literal.
更多回答(1 个)
Arif Hoq
2022-3-2
try this:
C=cell(8,2);
j = 1;
for m = [1:8]
C{m,1}=strcat('fn','_',num2str(j));
C{m,2}=strcat('file name',num2str(j),'_','txt');
j = j+1;
end
out=string(C)
2 个评论
Stephen23
2022-3-2
编辑:Stephen23
2022-3-2
Not very robust. Consider what would happen if the numbers change to [2,3,6,7,8].
- The variable m should not be used as the index: the values from the vector should be used to generate the filenames, then if the vector changes, the code would still work (well, mostly... it still needs NUMEL or similar).
- The variable j should be used as the index. Then it would correctly allocate to the output cell array, regardless of the vector values.
- Replace slow STRCAT with much faster SPRINTF.
- Those square brackets are completely superfluous. Get rid of them.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Characters and Strings 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!