MATLAB Answers

how to write a function with loop for and if-statement ?

3 views (last 30 days)
A Achbak
A Achbak on 7 Nov 2020
Commented: A Achbak on 19 Nov 2020
Hi, I need to write a function U like this :
if x=0 then U(0,y)=0
if y=0 then U(x,0)=0
if y=10 then U(x,10)=sin(pi*x/L).*sin(pi*10/L) for x=[0,L/2]
if x=10 then U(10,y)=sin(pi*y/L).*sin(pi*10/L) for y=[0,L/2]
if y=5 then U(x,5)=sin(pi*x/L).*sin(pi*5/L) for x=[L/2,L]
if x=5 then U(5,y)=sin(pi*y/L).*sin(pi*5/L) for y=[L/2,L]
So, i have a vector of x and y, for example x=[0 0 0 0 1 ....5....10..0..1..5....0] and y=[0 0 0 0 1 ....5....10..0..1..5....0], and npt=size(x)=size(y). I did code about it but it not work
function z= U(npt,x,y,L)
for m=1:npt
if( x(m)==0)
z=0;
end
end
for m=1:npt
if x(m)==L
z= sin(pi*y/L).*sin(pi*10/L);
end
end
for m=1:npt
if y(m)==0
z=0;
end
end
for m=1:npt
if y(m)==L
z = sin(pi*x/L).*sin(pi*10/L);
end
end
for m=1:npt
if x(m)==L/2
for y(m)=L/2:L
z= sin(pi*5/L).*sin(pi*y/L);
end
end
end
for m=1:npt
if y(m)==L/2
for x(m)=L/2:L
z = sin(pi*5/L).*sin(pi*x/L);
end
end
end
end

Accepted Answer

David Hill
David Hill on 7 Nov 2020
function z= U(x,y,L)
U=zeros(size(x));
U(x==10&y>=0&y<=L/2)=sin(pi*y(x==10&y>=0&y<=L/2)/L)*sin(pi*10/L);
U(y==10&x>=0&x<=L/2)=sin(pi*x(y==10&x>=0&x<=L/2)/L)*sin(pi*10/L);
U(x==5&y>=L/2&y<=L)=sin(pi*y(x==5&y>=L/2&y<=L)/L)*sin(pi*5/L);
U(y==5&x>=L/2&x<=L)=sin(pi*x(y==5&x>=L/2&x<=L)/L)*sin(pi*5/L);
end
  5 Comments

Sign in to comment.

More Answers (0)

Products


Release

R2016b

Community Treasure Hunt

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

Start Hunting!