How can I define a piecewise function by using Matlab

3 views (last 30 days)
How can I define piecewise function by using matlab and use it than to calculate Galerkin method my attempt was as follow:
clc;
clear all,
close all,
g=1;
syms x;
% this is piecewise function
% y=[y1 y2 y3];
% If (x>=-1 && x<=-0.5) then
y1=(2*x)+2;
% If (x>=-0.5 && x<=0) then
y2= -2*x;
% If (x>=0 && x<=1) then
y3=0;
% % % % %
% z=[z1 z2 z3 z4];
% If (x>=-1 && x<=-0.5) then
z1=0;
% If (x>=-0.5 && x<=0) then
z2= 1+2*x;
% If (x>=0 && x<=0.5) then
z3=1-2*x;
% If (x>=0.5 && x<=1) then
z4=0;
% % % % %
% q=[q1 q2 q3];
% If (x>=-1 && x<=0) then
q1=0;
% If (x>=0 && x<=0.5) then
q2= 2*x;
% If (x>=0.5 && x<=1) then
q3=2-2*x;
% % % % %
C(1,1)= int(((diff(y1))^2),-1,-0.5)+ int(((diff(y2))^2),-0.5,0);
C(2,2)= int(((diff(z2))^2),-0.5,0)+ int(((diff(z3))^2),0,0.5);
C(3,3)= int(((diff(q2))^2),0,0.5)+ int(((diff(q3))^2),0.5,1);
C(1,2)= int(((diff(y2))*(diff(z2))),-0.5,0);
% it is symmtric
% C(2,1)= int(((diff(z2))*(diff(y2))),-0.5,0);
C(2,1)=C(1,2);
C(1,3)= 0;
C(3,1)= 0;
C(2,3)= int(((diff(z3))*(diff(q2))),0,0.5);
% it is symmtric
% C(3,2)= int(((diff(q2))*(diff(z3))),0,0.5);
C(3,2)=C(2,3);
f(1,1)=(int(y1,-1,-0.5))+(int(y2,-0.5,0));
f(2,1)=(int(z2,-0.5,0))+(int(z3,0,0.5));
f(3,1)=(int(q2,0,0.5))+(int(q3,0.5,1));
X=inv(C)*f
Any help will be appreciate

Answers (1)

Walter Roberson
Walter Roberson on 30 Jul 2015
Example (untested)
pw = feval(symengine, 'piecewise', '([x < 0 or x > 1, 0], [x >= 0 and x <= 1, 1])');

Products

Community Treasure Hunt

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

Start Hunting!