필터 지우기
필터 지우기

problem in defining functional with one input as function

조회 수: 1 (최근 30일)
Lovelesh Lovelesh
Lovelesh Lovelesh 2021년 5월 4일
답변: Vatsal 2024년 5월 10일
I am trying to solve schrodinger equation using RK4 method my function is giving me error saying
Error using psi
K must be a scalar.
for t=1:Nt
psi_dasht=@(t,psi)(i.*((psi(X+dx,t)+psi(X-dx,t)-2.*psi(X,t))/2*dt^2 -V.*psi(X,t)));
k1=psi_dasht(X,psi(X,t));
k2=psi_dasht(X,psi(X,t)+0.5*dt.*k1);
k3=psi_dasht(X,psi(X,t)+0.5*dt.*k2);
k4=psi_dasht(X,psi(X,t)+dt.*k3);
psi(X,t+dt)=psi(X,t)+(dt/6).*(k1+2.*k2+2.*k3+k4);
end
function [a]=psi(x,t)
[a(t)]=(exp(-(x).^2/(2*4))/sqrt(2*pi*4));
end

답변 (1개)

Vatsal
Vatsal 2024년 5월 10일
Hi,
On running the provided code, I got the following error:
Declaring a variable with the same name as the local function "psi" is not supported in scripts.
The code uses "psi" as a function name and also as a variable to store values. You need to differentiate between the function "psi" and the variable that stores its values.
Here is a revised version of the provide code assuming "psi" is meant to be a matrix:
% Define the initial condition for psi
psi = zeros(length(X), Nt); % Preallocate psi for all X and t
psi(:,1) = initial_psi(X);
for t = 1:Nt-1
psi_dasht = @(X,psi) (i.*((psi([2:end, 1]) + psi([end, 1:end-1]) - 2.*psi)./dx^2 - V.*psi));
k1 = psi_dasht(X, psi(:,t));
k2 = psi_dasht(X, psi(:,t) + 0.5*dt.*k1);
k3 = psi_dasht(X, psi(:,t) + 0.5*dt.*k2);
k4 = psi_dasht(X, psi(:,t) + dt.*k3);
psi(:,t+1) = psi(:,t) + (dt/6).*(k1 + 2.*k2 + 2.*k3 + k4);
end
% Define the initial_psi function
function psi_initial = initial_psi(X)
psi_initial = exp(-X.^2 / (2*4)) / sqrt(2*pi*4);
end
I hope this helps!

카테고리

Help CenterFile Exchange에서 Operating on Diagonal Matrices에 대해 자세히 알아보기

제품


릴리스

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by