How to write piecewise function in matlab for the following function. Please give me matlab code.

5 ビュー (過去 30 日間)
clc
clear all
close all
syms x y
zeta0 = 0.5
L = 100;
W = 100;
h = 2;
g = 0.0098;
vt=sqrt(g*h)
c=1
v=c*vt
t1 = L/v
t = t1;
T1 = zeta0*v*t/(2*L)*(1-cos(pi/50*x)).*(1-cos(pi/100*(y+150))) ;
T2 = zeta0*v*t/L*(1-cos(pi/50*x)) ;
T3 = zeta0*v*t/(2*L)*(1-cos(pi/50*x)).*(1-cos(pi/100*(y-150))) ;
T = piecewise(0<=x<=100 , -150<=y<=-50, T1, 0<=x<=100 , -50<=y<=50, T2,0<=x<=100 , 50<=y<=150, T3)
fplot(T)

採用された回答

Star Strider
Star Strider 2020 年 6 月 14 日
Creating an anonymous function for ‘T’ is much easier and faster than using piecwise and the Symbolic Math Toolbox for this:
zeta0 = 0.5
L = 100;
W = 100;
h = 2;
g = 0.0098;
vt=sqrt(g*h);
c=1;
v=c*vt;
t1 = L/v;
t = t1;
T1 = @(x,y) zeta0*v*t/(2*L)*(1-cos(pi/50*x)).*(1-cos(pi/100*(y+150))) ;
T2 = @(x,y) zeta0*v*t/L*(1-cos(pi/50*x)) ;
T3 = @(x,y) zeta0*v*t/(2*L)*(1-cos(pi/50*x)).*(1-cos(pi/100*(y-150))) ;
T = @(x,y) ((0<=x) & (x<=100) & (-150<=y) & (y<=-50)).*T1(x,y) + ((0<=x) & (x<=100) & (-50<=y) & (y<=50)).*T2(x,y) + ((0<=x) & (x<=100) & (50<=y) & (y<=150)).*T3(x,y);
[X,Y] = ndgrid(-100:5:200);
figure
surf(X,Y,T(X,Y))
grid on
See Anonymous Functions for details, if you are not familiar with them
.

その他の回答 (1 件)

Aditya Verma
Aditya Verma 2020 年 6 月 14 日
編集済み: Aditya Verma 2020 年 6 月 14 日
Hello there!
You can code a piecewise function using conditional statements. More specifically, using if-else clause in this case. An example of absolute value function would be:
function val = absVal(x)
if x >= 0
val = x;
else
val = -x;
end
end
In a similar way, you can code your function.
If you are new to this concept, I recommend you to take the free MATLAB Onramp course, it will help you to get started with MATLAB.
UPDATE
If you have Symbolic Math Toolbox, you can use it to define this function in a similar way as you have mentioned. You can find similar examples here: https://www.mathworks.com/help/symbolic/piecewise.html#bu_gw85-1.

カテゴリ

Help Center および File ExchangeAssumptions についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by