Inputname() in Nested Functions: how to integrate the Input variable name of a function in a ".txt" file (opened in the function) when the input itself comes form a loop-function?

2 views (last 30 days)
I have a main function (function1) that prints the results in a .txt file named with the inputname of function1. because I need to do evaluations for many differend variables, I use a second function with a loop (function 2). The input values for function1 are in the base workspace:
function [] = function2()
s=['a';'b';'c';'d']
for j=1:length(s)
function1(evalin('base',strcat(s(j,:))))
end
end
and
function [O] = function1(I)
[...]
inputn=inputname(1);
out=fopen(['function1_',inputn,'.txt'],'wt');
fprintf(out,'..results..');
fclose(out);
[...]
end
If i use only function1(a), a text-file is created that is called function1_a.txt If i use the loop, the name of the text-file doesn't change and is just called "function1_.txt" (overwrites the file with each iteration in function 2). I know, there might be smarter ways to code without evalin(...) but this worked so far...
How can I get a new .txt file for every single Input variable (function1_a.txt, function1_b.txt,...)? (R2012)
Many thanks for your help, kind regards Jo.

Accepted Answer

Stephen23
Stephen23 on 6 Dec 2014
Edited: Stephen23 on 6 Dec 2014
The answer is simple: do not do this. In MATLAB it is (almost always) better to not create variable names on the fly:
Alternatives usually involve accumulating data in an array (which could be a struct or cell), of course with array preallocation. This page gives excellent examples about how you can do this:
Have a think about:
  • The starting conditions (data files and locations, etc)
  • The required data processing (merge data, apply operations, etc)
and then come back to MATLAB Answers asking what the best structure and processing would be to manage and process your data. Well planned data and processing is clear to follow, shows the intent of the processing and will be adaptable to change.

More Answers (0)

Categories

Find more on Programming 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!