# 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

조회 수: 7 (최근 30일)
JoeKay 2024년 4월 30일
편집: VBBV 2024년 4월 30일
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

댓글을 달려면 로그인하십시오.

### 답변 (1개)

VBBV 2024년 4월 30일
편집: VBBV 2024년 4월 30일
h = h + (1/6) * (k1 + 2*k2 + 2*k3 + k4);
% <> multplication operator is missing here
##### 댓글 수: 1이전 댓글 -1개 표시이전 댓글 -1개 숨기기
VBBV 2024년 4월 30일
implicit multipiication is not allowed in Matlab expressions

댓글을 달려면 로그인하십시오.

### 카테고리

Help CenterFile Exchange에서 Ordinary Differential Equations에 대해 자세히 알아보기

### Community Treasure Hunt

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

Start Hunting!

Translated by