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?

조회 수: 3 (최근 30일)
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.

채택된 답변

Stephen23
Stephen23 2014년 12월 6일
편집: Stephen23 2014년 12월 6일
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.
  댓글 수: 2
Jo
Jo 2014년 12월 9일
Ok thank you Stephen for your hints. I'll change my variable notations.. Regards Jo
Stephen23
Stephen23 2014년 12월 20일
If you are not sure how to structure your data in MATLAB, feel free to ask a new question :)

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Startup and Shutdown에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by