How do i create variables from strings for the purpose of writing different variables to text file.
4 次查看(过去 30 天)
显示 更早的评论
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 个评论
Stephen23
2018-9-3
编辑:Stephen23
2018-9-3
"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.
采纳的回答
Stephen23
2018-9-3
编辑:Stephen23
2018-9-3
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 个评论
Stephen23
2018-9-3
@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!
更多回答(0 个)
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!