Nested FOR Loop Help

1 次查看(过去 30 天)
James
James 2015-7-7
编辑: bio lim 2015-7-8
I would like to vary the value of a parameter in my model that was originally a static variable by using a nested FOR loop. I am testing the model sensitivity to the parameter, and I would eventually like to vary two variables using another FOR loop. If this is not the best way to go about this, I am happy to hear suggestions. I want the second FOR loop to run all iterations using the first value in the first FOR loop and once it is done I want the second FOR loop to run the second value.
When I run the code I get this ERROR: Attempted to access uplift_rate(2); index out of bounds because numel(uplift_rate)=1.
My code looks like this:
uplift_rate = [1e-2, 2e-2]
for i=1:numel(nColumns);
uplift_rate_i = uplift_rate(i)
for j=1:nSteps;
y = y+(uplift_rate_i(j)*dt); %new height
% calculate water depth, h1
h=SL(nSteps-j+1)-y;
end
end
Thank you in advance for the help.
  1 个评论
Stephen23
Stephen23 2015-7-8
Note that you should avoid using i and j for variable names (e.g. loop variables), as these are both names of the inbuilt imaginary unit.

请先登录,再进行评论。

回答(1 个)

bio lim
bio lim 2015-7-8
I don't really understand your code. What is the purpose of the first loop? I think every time it loops ( i = 1 : numel(nColums) it is overwriting the scalar in uplift_rate_i, and that i is not indexing. It is part of your array name. Therefore, the second loop is also not going to work because,
numel(uplift_rate_i) = 1
uplift_rate_i(j) for j ~=1 don't exist.
I think you should upload your program.
  1 个评论
bio lim
bio lim 2015-7-8
编辑:bio lim 2015-7-8
Initial Conditions:
dt=100;
tmax = 1400000;
t=0:dt:tmax;
nSteps=numel(t);
Your first loop is as follows.
for i=1:numel(nColumns);
uplift_rate_i = uplift_rate(i)
In here, nColumns = 2. What you are doing here can already be obtained from the indexing, and therefore I don't understand why you are assigning a variable to the elements. In other words, I think this loop is not necessary. You can simply use uplift_rate(1) and uplift_rate(2).
For the second loop
for j=1:nSteps;
y = y+(uplift_rate_i(j)*dt);
h=SL(nSteps-j+1)-y;
end
From your initial condition, you can see that nSteps = 14001, which is far larger than length(uplift_rate) = 2. Therefore, index more than 2 doesn't exist.
What I think is that you might have defined your uplift_rate matrix wrong from the start.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by