How to use placeholder in a loop?
18 views (last 30 days)
Show older comments
Hello, I've problems creating a loop and I didn't found any right answer for this.
I have a matrice with 7 columns.
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/159766/image.png)
The first is the time and the others are 6 different reactions. They were started at different times, so every of this 6 columns has much space filled with zeros. I want to cut them out. I have to plot every reaction against the first column (time). So I separated the columns for each reaction. I already built the code for deleting the zeros. But now I want to build a loop which runs automatically through all the separated variables. The only thing to change is the number at the end.
So my Idea was to set a placeholder for the number and let the loop run 6 times. Every round it should replace the x with the next number. But as you can see it doesn't accept this method in combination of the name of the reaction matrice. It doesn't work either when I change the name in one simple letter.
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/159767/image.png)
How can I fix this problem?
1 Comment
Answers (2)
Chinmayi Lanka
on 19 Jan 2017
From what I understand, in your loop, you want the variable Ansatzx_f to be Ansatz1_f in the first iteration, Ansatz2_f in the second iteration and so on. If you use 'Ansatzx_f' it will assume it to be a separate variable and hence the error.
One option is to use the 'eval' function, for example:
>> eval(['Ansatz',num2str(index),'_f'])
However, the recommended approach is to use structures:
>> Ansatz = struct;
>> Ansatz.1_f = Probenkurve(:,1:2);
>> Ansatz.2_f = Probenkurve(:,1:2);
..
..
..
Store the list of fieldnames in a variable outside the loop and index the fieldnames inside the loop:
>> names = fieldnames(Ansatz);
>> for index = 1:maxNum
>> ans = getfield(Ansatz,names{index});
>> end
0 Comments
Stephen23
on 19 Jan 2017
Edited: Stephen23
on 19 Jan 2017
>> S.data1 = 123;
>> S.data2 = 4:6;
>> S.data3 = NaN;
>> S.(sprintf('data%d',2))
C = cell(1,10);
C{1} = 123;
C{2} = 4:6;
C{3} = NaN;
C{2}
Note how easily this can be done in a loop:
for k = 1:numel(C)
C{k}
end
I guarantee that this will be a thousand times easier, faster, and more reliable than any slow, buggy hack code that you could come up with to try and create those variable names in a loop. Read this to know why:
For some reason beginners often dream up the idea of dynamically accessing variable names, and are often convinced that it will solve all of their problems. In reality it just creates different problems.
0 Comments
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!