Clear Filters
Clear Filters

I am getting the following error when I run my script: Invalid expression. When calling a function or indexing a variable, use parentheses. Otherwise, check for mismatc

1 view (last 30 days)
I'm running the following script in Matlab and getting the following error message:
h = h + (1/6) (k1 + 2k2 + 2*k3 + k4);
Invalid expression. When calling a function or indexing a variable, use parentheses.
Otherwise, check for mismatched delimiters.
Could you please assist me with clearing the error.
% Given data
h0 = 4.84; % Initial height (m)
t0 = 0; % Initial time (hrs)
tf = 15; % Final time (hrs)
h_target = 3.5; % Target height (m) after 3.5 hrs
% Function representing the differential equation
dhdt = @(t, h, k) k * sqrt(h);
% Runge-Kutta method
h = h0;
t = t0;
k = 0; % To be determined
tolerance = 1e-6;
while t < 3.5
k1 = dhdt(t, h, k);
k2 = dhdt(t + 0.5, h + 0.5 * k1, k);
k3 = dhdt(t + 0.5, h + 0.5 * k2, k);
k4 = dhdt(t + 1, h + k3, k);
h = h + (1/6) * (k1 + 2*k2 + 2*k3 + k4);
t = t + 1;
k = (h_target - h) / (tf - t); % Adjusting k based on target height
end
% After 3.5 hours
fprintf('Height after 3.5 hours: %.4f m\n', h);
Height after 3.5 hours: 4.2815 m
% Continue solving until tf
while t < tf
k1 = dhdt(t, h, k);
k2 = dhdt(t + 0.5, h + 0.5 * k1, k);
k3 = dhdt(t + 0.5, h + 0.5 * k2, k);
k4 = dhdt(t + 1, h + k3, k);
h = h + (1/6) * (k1 + 2*k2 + 2*k3 + k4);
t = t + 1;
end
% Display the final height
fprintf('Height after %.1f hours: %.4f m\n', tf, h);
Height after 15.0 hours: 2.8171 m

Answers (1)

VBBV
VBBV on 30 Apr 2024
Edited: VBBV on 30 Apr 2024
h = h + (1/6) * (k1 + 2*k2 + 2*k3 + k4);
% <> multplication operator is missing here

Community Treasure Hunt

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

Start Hunting!