how to open *.txt files with variable names
显示 更早的评论
hi I have a function '[dl]=funcall(x,y)' and in it I want to create *.text file with variable names and write out put vectors 'dl'. such as this
function [dl]=funcdl(x,y)
.........
fid=fopen('DL.txt', 'wt');
fprintf(fid, '%f\n',dl);
fprintf(fid, '\n');
fclose(fid);
......
but every time by calling function it creates the same name 'DL.txt' and overwrites out put!!! any one can help me???
采纳的回答
更多回答(1 个)
Gaurav Shukla
2014-10-13
Consider an array
VarName = [A,B,C];
for i=1:3
str = strcat('fopen(''',VarName(i),'.txt','wt');
eval(str);
end
14 个评论
Do NOT do this
This code includes multiple examples of bad MATLAB coding. Some of them are:
- The function eval should only be used as a last resort, and not for something as trivial as opening or writing a file. Poor use of the function eval comes in at first place on this list of bad coding practices.
- The loop-variable should not be named i, as this is the name of the inbuilt imaginary unit .
- This code does not flcose any of the files that it opens, leaving them open until MATLAB is closed.
Do NOT use this code
A better implementation would be:
for k=1:3
str = strcat('temp',num2str(k),'.txt');
fid = fopen(str,'wt');
...
... write data to your file here (fprintf, or whatever...)
...
fclose(fid);
end
Image Analyst
2014-10-13
I couldn't agree more - Gaurav's code sample is really bad code. Whoever he got that snippet from, he should stop getting code from that person.
You can use sprintf() (which I and C programmers prefer) as an alternative to strcat.
baseFileName = sprintf('temp%d.txt', k);
fullFileName = fullfile(folder, baseFileName);
fid = fopen(fullFileName,'wt');
Or if VarName is a cell array of strings:
baseFileName = sprintf('temp%s.txt', VarName{k});
fullFileName = fullfile(folder, baseFileName);
fid = fopen(fullFileName,'wt');
Andrew Reibold
2014-10-13
编辑:Andrew Reibold
2014-10-13
I was reading that list of coding practices that make at least Doug cry, and he didn't really explain why eval was bad. He was just kind of like 'There is already another way to do it, and that way is the 'right' way'. Yes sure, there is another way to do it. A way that is less clear to noobies and takes more time for them to use.
Eval is frankly much easier to understand and hasn't caused any issues in my experience.. . That is why it is so popular. I don't get why people hate on it so much.
Who cares if you open file names with eval if it works and its easy and its fast. Isn't that what we want? Fast, easy, effective? I open file names with eval all the time and it works like a charm. And the amount it takes to read a file is much larger than the time it takes to run an eval function so much so that the time it takes to run eval is negligible.
Also, complaining his code is ineffective for using 'i' is pretty trivial. Obviously its just an example... and he can use ii, cat, whale, or bad_coding_practice_here if he wanted. If he is using imaginary numbers at all he probably knows better or will soon find out there is an issue.
- It isn't fast, it is slower than just calling any function directly.
- It obscures the code intent. Totally.
- It is not compiled for optimized running. Every call has to eval all over again!
- It makes debugging almost impossible.
- It can produce different outputs in normal and debug modes.
- It can create and overwrite variables in workspaces.
- It usually seems to be associated with other practices that are not an efficient use of MATLAB... sequential variable names, for example.
These topics have been covered many times in MATLAB's official documentation, blogs and other discussions:
So when is the right time to learn good coding practices?
Sure they can use i. Then one day they merge their code with others', or join a team doing joint development, or tries to integrate someone's code into their work... and bingo, it all stops working. That team will be delighted to waste its time re-teaching basic MATLAB coding practices.
Andrew Reibold
2014-10-13
编辑:Andrew Reibold
2014-10-13
The speed difference is negligible when using it to open file names. You say it obscures code intent, but looking between Gaurav's example and both of yours... his was easier to immediately understand and see the intent of. 'Seeming to be associated with other practices that are not an efficient use of matlab' is irrelevant to the use of the function itself..' The other issues i have personally never had issues with.
I think it depends on the extent of your use and your plans for future use. If he is going to be spending the next year at a job using matlab and opening tons of file names maybe another solution is right for him. But for this one off example, eval is a fast, simple, effective, clear solution.
The code that Gaurav Shukla wrote includes this line:
str = strcat('fopen(''',VarName(i),'.txt','wt');
However it is wrong code: that string, when evaluated, produces an error, as it is also missing the closing bracket. Did anyone spot this? Was it easy to see, or is it obfuscated in the middle of the ton of brackets and quotation marks? Perhaps they also noticed that this string has the wrong number of quotation marks? More likely they lost track trying to figure out how many quotation marks it needs, just like its author did.
Two major syntax errors in one line of code, due to the obfuscation allowed by using eval. If the function had been called directly, then MATLAB's code editor would simply highlight these coding errors, but it can't do that here because the code is obfuscated in a string: unfortunately the code was NOT actually "easier to immediately understand and see the intent of"! What a shame that its author could not use any of MATLAB's automatic code hinting, could not rely on the syntax checking in the editor, and could not press the F1 key to bring up the help for the function that they were currently typing...
For those who are curious, the error occurs only when the eval statement is called:
>> eval(str);
Error: A MATLAB string constant is not terminated properly.
There is no indication where, or on which line, or in what function this error occurs, or how I could try to find it and fix it... how does this support the argument that "for this one off example, eval is a fast, simple, effective, clear solution" when it doesn't work and it isn't clear how to fix it?
Good coding doesn't depend only on "plans for future use", but making the best use of all of MATLAB's tools and help, including optimizing, debugging, mlint, etc.
There is no better day than today to start learning good coding practices.
Stephen23
2014-10-13
For new readers, read all of these comments and
Do NOT use this code
Robert Cumming
2014-10-13
+1 for Stephen Cobeldick reasoning on why the example is really bad and why eval should be avoided.
+1 for ImageAnalyst avocation of sprintf - I also prefer it (+ its a lot faster).
In this example the speed improvement of using fopen or sprintf may not appear that key - but its the lessons you learn now that will be beneficial in the future.
A real life example for you - A colleague of used strcat or [ 'A' 'B' ] to manipulate strings (despite me encouraging sprintf for a long time. He then had a project which was taking too long to run so he asked me to look at it for him (it was taking ~50 mins per run).
I spent a few hours looking at it and using a number of techniques I had learned over the years (one of which was converting all string operations to sprintf) I was able to reduce the runtime to ~18 minutes.
Andrew Reibold
2014-10-13
编辑:Andrew Reibold
2014-10-13
All I'm saying is that I could glance at his, and understand what was going on right away. I could stare at the others, and after analyzing what they were doing, understand what was going on.
Ok, so there was an extra apostrophe or something. I didn't try it because it was so easy to fundamentally see what was happening. That simple mistake could happen anywhere and is a really easy fix...
I mean, as long as you use eval correctly, it works great. Just like everything else in coding..
And if you need to do this 800,000 times, then of course eval will be slower. But if its only a few, you aren't going to notice the difference beteen .0002 and .003 seconds or whatever it may be.
I'm all for good coding practice, but at the same time when you need a fast, effect, simple, easy to understand solution for a quick job, sometimes being an elitist about your code is more of a hinderance and bottleneck then anything else.
Stephen23
2014-10-13
How is using MATLAB's inbuilt tools "being an elitist"?
These tools are there to help all users, even the learners: code hinting, links to help, error messages, mlint messages, optimized compiling, etc. And it is precisely because a "simple mistake could happen anywhere" that MATLAB (and other programming languages) have developed tools to help minimize, find and fix these errors. How exactly is it "elitist" to use these?
Using eval for trivial functions in MATLAB takes all of these tools away, which when combined with the code obfuscation and hidden intent and the other disadvantages, really does make it a poor habit to get into. And like all bad habits, it is hard to change later. For more complicated code, it really will matter.
I am genuinely curious: can you please provide an example of when good coding practice is "more of hinderance and bottleneck then anything else"?
Stephen23
2014-10-13
For new readers, read all of these comments and
Do NOT use this code
Andrew Reibold
2014-10-13
编辑:Andrew Reibold
2014-10-13
You don't have the experience to come up with a single example? Or is this just an attempt at rhetoric..
How about this example (from one of your own questions):
In a comment to one of the answers to that question you write "Its just that the code I inherited is just an absolute catastrophe when it comes to formatting and practice".
This seems to contradict your earlier comment on this thread: "I'm all for good coding practice, but at the same time when you need a fast, effect, simple, easy to understand solution for a quick job, sometimes being an elitist about your code is more of a hinderance and bottleneck then anything else".
And yet it seems that someone else's "fast, effect[ive], simple" solution became your "absolute catastrophe" problem to solve, which really did cause you a "hinderance and bottleneck" : not because it was well written code, but because it was poorly written code and because this is usually what poorly written and obfuscated code does.
MATLAB's inbuilt tools help to avoid basic syntax mistakes, which goes part of the way to writing good code. So, dear reader, why not use them?
Stephen23
2015-1-4
For new readers, read all of these comments and
Do NOT use this code
类别
在 帮助中心 和 File Exchange 中查找有关 String Parsing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!