How to use placeholder in a loop?

28 次查看(过去 30 天)
jeferia_tue
jeferia_tue 2017-1-13
编辑: Stephen23 2017-1-19
Hello, I've problems creating a loop and I didn't found any right answer for this.
I have a matrice with 7 columns.
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.
How can I fix this problem?

回答(2 个)

Chinmayi Lanka
Chinmayi Lanka 2017-1-19
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

Stephen23
Stephen23 2017-1-19
编辑:Stephen23 2017-1-19
You could use structure fields:
>> S.data1 = 123;
>> S.data2 = 4:6;
>> S.data3 = NaN;
which can also be defined dynamically:
>> S.(sprintf('data%d',2))
but to be honest a much better solution is to use a cell array:
C = cell(1,10);
C{1} = 123;
C{2} = 4:6;
C{3} = NaN;
and then simply accessed using indexing:
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.

Community Treasure Hunt

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

Start Hunting!

Translated by