简体   繁体   中英

Defining piecewise function in Matlab

I'm trying to use a soliton plus a step for my initial condition for KdV equation, however when I try running the code, it is unable to execute my first order difference scheme. I believe the issue is with how I defined my step function H(x)-which is a piecewise function, using 'syms'. I include a sample of my code below for reference.

close all
clear
clc
% Generating grid with n points, with the space between two points being
%(x2-x1)/(n-1)
x = linspace(-5,5,1001); 
N=1001;
h=x(2)-x(1); % grid size
dt=0.05;
%Soliton initial condition
Am=8; %Amplitude
mu=sqrt(Am/2);
x0=-15;
c=1;
syms H(x)
H(x)=piecewise(x < 0,0,x > 0,1);
u= Am*(sech(mu*(x'))).^2+c^2*H(x);

% Creating a matrix A - First order
A = diag(ones(N-1,1),1)-diag(ones(N-1,1),-1);
Cvector = zeros(N, 1);
Cvector(end) = 1;
u_ic = Cvector;

% First order finite difference scheme
diff_first=A*u/(2*h)+1/(2*h)*u_ic;

I am new to Matlab so I am not sure if my use of syms is correct in this context.

I can't know this without more information, but I suspect that the issue is that you're trying to use x in a symbolic expression when you've already defined x as a variable. Instead, replace

syms H(x)
H(x)=piecewise(x < 0,0,x > 0,1);

with

syms y
H(y) = piecewise(y<0,0,y>=0,1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM