How do i create variables from strings for the purpose of writing different variables to text file.
3 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Thomas Dixon
am 3 Sep. 2018
Kommentiert: Stephen23
am 3 Sep. 2018
I want to be able to do something like choose scenario a and get 5 text files with the numbers 1,2,3... 2,2,3... 3,2,3... 4,2,3... 5,2,3 and then with the same hardcode but in a new run choose the letter b and now produce 5 text files like 1,1,3... 1,2,3... 1,3,3... 1,4,3... 1,5,3. Any help on this matter is greatly appreciated. My not working attempt is shown below.
My thought process is to try to redefine a vraiable name by reading the string I enter, making a variable called that string (overwriting the predefined ones) and then trying to somehow make that the argument of the for loop.
a = 1
b = 2
c = 3
prompt = 'what would you like to sweep over\r\n'
sweepstr = input(prompt,'s')
sweep = genvarname(sweepstr)
for sweep = 1:1:5
filename = sprintf('test%s%i.txt',sweepstr,sweep);
circuitfile = fopen(filename,'w');
fprintf(circuitfile,' %i \r\n %i \r\n %i',a,b,c);
fclose(circuitfile);
end
Thanks in advance for all and any help
1 Kommentar
Stephen23
am 3 Sep. 2018
Bearbeitet: Stephen23
am 3 Sep. 2018
"My thought process is to try to redefine a vraiable name by reading the string I enter, making a variable called that string (overwriting the predefined ones) and then trying to somehow make that the argument of the for loop"
That would be a pointlessly difficult, slow, complex, buggy, and hard to debug way to try and solve this problem. Here is why this approach is not recommended:
A much simpler approach is to put the data into one small vector and use indexing. Then this task is trivial to solve, using neat and highly efficient indexing.
Akzeptierte Antwort
Stephen23
am 3 Sep. 2018
Bearbeitet: Stephen23
am 3 Sep. 2018
This is trivial when you put those values into one small vector. Then you can use indexing very simply:
V = [1,2,3];
S = input('var to sweep (1/2/3): ','s');
X = str2double(S);
for k = 1:5
V(X) = k;
fprintf('%d\n%d\n%d\n',V)
end
Tested:
>> temp0
var to sweep (1/2/3): 3
1
2
1
1
2
2
1
2
3
1
2
4
1
2
5
If you want to let the user select a name rather than an index, then just add strcmp, something like this:
S = input('var to sweep (a/b/c): ','s');
X = find(strcmp(S,{'a','b','c'}));
Tested:
>> temp1
var to sweep (a/b/c): c
1
2
1
1
2
2
1
2
3
1
2
4
1
2
5
4 Kommentare
Stephen23
am 3 Sep. 2018
@Thomas Dixon: I hope that it helps. Structures are highly recommended for handling lots of parameters like this: they make them easy to access, to pass to/from functions, and intuitive to read/understand.
Questions are always welcome, that is why we are here!
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Variables finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!