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
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
Rik 2021년 6월 10일

2 개 추천

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

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Data Type Conversion에 대해 자세히 알아보기

질문:

2021년 6월 10일

편집:

2021년 6월 10일

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by