error in for loop

15 次查看(过去 30 天)
hossein
hossein 2024-2-19
编辑: Torsten 2024-2-20
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
u for R = -10.00: -394000.000000
Index exceeds the number of array elements. Index must not exceed 1.
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)));

回答(1 个)

Torsten
Torsten 2024-2-19
移动:Torsten 2024-2-19
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 个评论
Walter Roberson
Walter Roberson 2024-2-19
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
Torsten 2024-2-19
编辑:Torsten 2024-2-20
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.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by