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 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
niniki
am 2 Mär. 2022
Kommentiert: Stephen23
am 3 Mär. 2022
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 Kommentare
Akzeptierte Antwort
Stephen23
am 2 Mär. 2022
Bearbeitet: Stephen23
am 2 Mär. 2022
"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 Kommentare
Stephen23
am 3 Mär. 2022
"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.
Weitere Antworten (1)
Arif Hoq
am 2 Mär. 2022
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 Kommentare
Stephen23
am 2 Mär. 2022
Bearbeitet: Stephen23
am 2 Mär. 2022
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.
Siehe auch
Kategorien
Mehr zu Characters and Strings finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!