Use of evalc with num2str
4 views (last 30 days)
Show older comments
Hello everyone
I am trying to use evalc to retrieve a file from a folder filled with files.
I have multiple files that are named as follows:
14122017_Rutherford_data_559_F-trigma_1957_008_data.csv
If I do
evalc('dir *data.csv*')
then I am able to get every single file in this folder. However I only want to output files which end with 1957_008_data.csv
Therefore, if I do
evalc('dir *1957_008_data.csv*')
- this works for me.
The issue is: this folder has files for different years (1957 and others) and different codes (008 and others), so I want a way to somehow be able to use evalc to get files where the user selects the pick_year and pick_code. For example the following will give 1957_008_data.csv as output but I don't know how to use eval with this. Could someone help me with the syntax of how to use the following in evalc. Thank you. Su
[num2str(pick_year) '_' num2str(pick_code) '_data.csv']
1 Comment
Stephen23
on 11 Dec 2017
What is the point in using evalc in this code? This seems to serve absolutely no purpose whatsoever, apart from making your code complex, slow, buggy (you cannot make it work, ergo buggy), insecure, and hard to debug (clearly you could not solve this bug yourself).
Accepted Answer
Walter Roberson
on 11 Dec 2017
year = 1957;
code = 8;
pattern = sprintf('*%04d_%03d_data.csv');
dinfo = dir(pattern);
filenames = {dinfo.name};
Notice the complete lack of evalc() anywhere in the code.
2 Comments
Walter Roberson
on 11 Dec 2017
To get the date information:
dates = cellfun(@(S) sscanf(S, '%d'), filenames);
This assumes that there might be more than one matching date. If the resulting vector is empty then there were no matching files.
More Answers (2)
Steven Lord
on 11 Dec 2017
Do NOT use eval, evalc, or any other function in the eval family. Just call dir as a function with an input argument and an output argument, then iterate through the elements of the struct array returned as output. See the "Find Information in the Return Structure" example on the documentation page for dir for some code you can adapt to your needs.
0 Comments
See Also
Categories
Find more on File Operations in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!