error in for loop

16 ビュー (過去 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 Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by