How to name variable with file name?
69 次查看(过去 30 天)
显示 更早的评论
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 个评论
Stephen23
2021-6-10
编辑:Stephen23
2021-6-10
"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.
采纳的回答
Rik
2021-6-10
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)
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Structures 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!