Using a for loop from i = 2:N producing Error
13 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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 Commento
Torsten
il 7 Dic 2023
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.
Risposte (1)
Udit06
il 21 Dic 2023
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 Commenti
Vedere anche
Categorie
Scopri di più su Matrix Indexing in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!