Hello, I am new to Matlab and I need help with an error that pops up when I try to run my code. I don't understand why the error "Index exceeds matrix dimensions" pops up for my equation solving for variable D.

In this problem I need to solve the system of equations for four unkowns V, D, Re, and f. An error saying the index exceeds matrix dimensions pops up for the line containing D(i) = (((f1(i)*240*(Name^2))/(pi^2*(4*9.81)))^(1/5)) and I am not sure why.
Name = (9+13/100);
df=0.0001;
f1_min=0.0001;
f1_max=1;
err0=10.01000;
f1=(f1_min:df:f1_max);
for i=1:length(f1)
D(i) = (((f1(i)*240*(Name^2))/(pi^2*(4*9.81)))^(1/5));
V(i) = Name/(pi*((D(i)^2)/4));
Re(i) = ((V(i)*D(i))/0.0001655);
err(i) = 1/sqrt(f1(i))+2.0*log10(2.51/(Re(i)*sqrt(f1(i))));
if abs(err(i))<=err0
err0=abs(err(i));
D=D(i)
Re=Re(i)
V=V(i)
f1=f1(i)
% f1t=f1(i)
end
end
plot(f1(1:i),err)
grid

Réponses (1)

Hi Isabel,
A couple of things. First, since you want to keep f1 as a vector for the plot, the f1 line in the 'if' statement needs to be commented out. Second, once the error criterion is satisfied, it's time to exit the for loop, so there needs to be a break statement:
if abs(err(i))<=err0
err0=abs(err(i));
D=D(i)
Re=Re(i)
V=V(i)
%f1=f1(i)
% f1t=f1(i)
break
end
With several of your variables, each time around the for loop you are appending a value at the end and building up the length that way. That's all right for as small a code as this is, but if the length is large this gets really slow. Better to preallocate memory before doing the for loop with D = zeros(1,length(f1)) etc.

Catégories

Community Treasure Hunt

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

Start Hunting!

Translated by