error in for loop
15 views (last 30 days)
Show older comments
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 Comments
Answers (1)
Torsten
on 19 Feb 2024
Moved: Torsten
on 19 Feb 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 Comments
Walter Roberson
on 19 Feb 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
on 19 Feb 2024
Edited: Torsten
on 20 Feb 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.
See Also
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!