How to name variable with file name?

44 Ansichten (letzte 30 Tage)
BOUCHE Jules
BOUCHE Jules am 10 Jun. 2021
Bearbeitet: Stephen23 am 10 Jun. 2021
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 Kommentar
Stephen23
Stephen23 am 10 Jun. 2021
Bearbeitet: Stephen23 am 10 Jun. 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.

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Rik
Rik am 10 Jun. 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)
ans = 3×2 table
filename m ______________ _______ {'file_1.txt'} 0.77989 {'file_2.txt'} 0.55155 {'file_3.txt'} 0.60934

Weitere Antworten (0)

Kategorien

Mehr zu File Operations 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!

Translated by