error in for loop

조회 수: 18 (최근 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