error in for loop
15 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
We want to fix the problem of the for loop in the code below without changing the boundary conditions. What is your suggestion? Thank you in advance.
clc;
clear;
close all;
R = linspace(-10, 10, 12);
h = 1e-3;
u_values = zeros(1, length(R)); % Array to store u values
% Calculate u for all R values
for j = 1:length(R)
u = (4 * R(j).^5) - (6 * R(j).^3); % Calculate u for current R
u_values(j) = u; % Store u value
fprintf('u for R = %.2f: %f\n', R(j), u);
if j==1
derivative = (1/(60*h) * (u(j+3) - u(j-3))) - (3/(20*h) * (u(j+2) - u(j-2))) + (3/(4*h) * (u(j+1) - u(j-1)));
end
end
this error:
Index exceeds the number of array elements (1).
Error in Untitled2 (line 17)
derivative = (1/(60*h) * (u(j+1) - u(j-1))) - (3/(20*h) * (u(j) - u(j-2))) + (3/(4*h) * (u(j) - u(j-1)));
0 comentarios
Respuestas (1)
Torsten
el 19 de Feb. de 2024
Movida: Torsten
el 19 de Feb. de 2024
u(j-3) is only defined for j>=4, u(j+3) is only defined for j<=length(R)-3. Similar restrictions hold for the other indices. Thus your loop must start with j = 4 and end with length(R)-3.
2 comentarios
Walter Roberson
el 19 de Feb. de 2024
if j==1
derivative = (1/(60*h) * (u(j+3) - u(j-3))) - (3/(20*h) * (u(j+2) - u(j-2))) + (3/(4*h) * (u(j+1) - u(j-1)));
If you start the loop at j = 4, then j==1 will never be true, so the derivative would never be calculated.
Torsten
el 19 de Feb. de 2024
Editada: Torsten
el 20 de Feb. de 2024
ok, I correct:
Thus your loop must start with j = 4, end with length(R)-3 and you can remove the if-statement.
Further, the vector u must be defined before entering the loop.
R = linspace(-10, 10, 120);
h = R(2)-R(1);
u = 4 * R.^5 - 6 * R.^3;
derivative = nan(size(u));
for j = 4:length(R)-3
derivative(j) = (1/(60*h) * (u(j+3) - u(j-3))) - (3/(20*h) * (u(j+2) - u(j-2))) + (3/(4*h) * (u(j+1) - u(j-1)));
end
hold on
plot(R,derivative)
plot(R,20*R.^4-18*R.^2,'o')
hold off
grid on
If you need derivatives nearer to the boundaries, you will have to use a method of lower order that uses a smaller stencil.
Ver también
Categorías
Más información sobre Creating and Concatenating Matrices en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
