Nested FOR Loop Help

조회 수: 3 (최근 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