Using a for loop from i = 2:N producing Error
13 次查看(过去 30 天)
显示 更早的评论
Hello, I am working on a project and getting the error:
Index exceeds the number of array elements. Index must not exceed 2.
Error in Final_Project (line 40)
Vel(i) = (A(h)*Vel(h)) / A(i);
This happens with:
x = linspace(0,2,20);
P(1) = 300;
Vel(1) = 5;
A(1) = (pi*((Dia(1)^2)/4));
N = length(x);
for i = 2:N
A(i) = (pi*((Dia(i)^2)/4));
Vel(i) = (A(i-1)*Vel(i-1)) / A(i);
P(i) = P(i-1) + (0.5*rho*Vel(i-1)) - (0.5*rho*v(i));
end
Is there a way to use a previous result without breaking the loop?
Thank you!
1 个评论
Torsten
2023-12-7
The line
Vel(i) = (A(h)*Vel(h)) / A(i);
is cannot be found in your code.
And we don't know whether Dia(i) and v(i) are somewhere else defined for i = 2,...,N.
回答(1 个)
Udit06
2023-12-21
Hi George,
I understand that you are facing an error which indicates that the index you are using is exceeding the number of array elements. After looking at the code provided above, I would recommend you to make the following changes in the code to resolve the issue.
- Define the variable "rho"
- Variable "Dia" is also not defined and you are not using variable "x" anywhere else in the code. Hence, you might consider replacing "x" with "Dia" in the code and defining "Dia" in such a way that it does not contain 0.
- P(i) = P(i-1) + (0.5*rho*Vel(i-1)) - (0.5*rho*v(i)); In this line of code, variable "v" is not defined.Consider replacing "v" with "Vel".
Here is the code after making the changes suggested above:
% Define "rho", change the value of "rho" as per your requirement
rho=1;
% Removed "x" as it was not used in your code, and defined an array for "Dia"
% Change "Dia" as per your requirements.
Dia = rand(1,20)+5;
P(1) = 300;
Vel(1) = 5;
A(1) = (pi*((Dia(1)^2)/4));
% Replaced "x" with "Dia"
N = length(Dia);
for i = 2:N
A(i) = (pi*((Dia(i)^2)/4));
Vel(i) = (A(i-1)*Vel(i-1)) / A(i);
%Replaced "v" with "Vel"
P(i) = P(i-1) + (0.5*rho*Vel(i-1)) - (0.5*rho*Vel(i));
end
You can refer to the following MathWorks documentation to understand more about "Undefined Function or Variable" error:
I hope this helps.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!