How to name variable with file name?
44 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Hi, i'm trying to make a code which create "mat" files from "cvs" automatically . I'm using an other program to to the conversion and i want to have a file and a variable automatically named. For example if i use "file1.csv" i want to get "file1.mat" which contain file1. I know how to name the file but not the variable.
Can someone help me or tell me a better way to do this please?
Here is my code:
for i=1:2;
m=txt2mat; % return the content of a specified file
save(['m_' num2str(i)],m);
end
1 Commento
Stephen23
il 10 Giu 2021
Modificato: Stephen23
il 10 Giu 2021
"How to name variable with file name?"
That is very buggy data design. Consider what happens if the file has one of these perfectly legal filenames:
1.csv
1-2.csv
@1.csv
quit.csv
a+b.csv
a(2).csv
Sure, you work on a limited set of filenames... then your colleague tries it with their files. Or in six months you forget this pointless filename restriction deep inside your code-base. Or you want to distribute your code and give other users a good impression. Why do you want to intentionally build latent bugs into your code?
"i want ... a variable automatically named"
Dynamically naming or accessing variable names is one way that beginners force themselves into writing slow, complex, obfuscated, buggy code which is difficult to debug. Your .mat file data will be much easier to process when the variable names are the same in every .mat file.
"Can someone help me or tell me a better way to do this please?"
Simple: do not change the variable names.
Risposta accettata
Rik
il 10 Giu 2021
You shouldn't do that. If you give all the same name, you will get a struct array when you load everything.
for file=1:3
m=rand;
filename=sprintf('file_%d.txt',file);
matfilename=sprintf('file_%d.mat',file);
save(matfilename,'m','filename')
end
clear S
for file=1:3
matfilename=sprintf('file_%d.mat',file);
S(file)=load(matfilename);
end
struct2table(S)
Più risposte (0)
Vedere anche
Categorie
Scopri di più su File Operations in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!