MATLAB: How to plot two conditions together

if statementtwo condititons

I have to plot when r<=a, psi = psi = (1/besselj(0,1.31689).*(besselj(0,1.31689.*(r/a)))); and for r>=a, psi= psi = (1/besselk(0,0.71819).*(besselk(0,0.71819.*(r1/a)))); I should get a continous plot. However, I am getting a curve in two colors, one for one statement and one for second. And also it should approach zero after r=a. My code looks like this, lambda=632*10^-9; k0=2*pi/lambda; n1=1.455; n2=1.45; a = 3*10^-6; u = 1.31689; w = 0.71819; N= 490; J = zeros(0,490); K=zeros(0,490); r = zeros(0,490); psi = zeros(0,490); psi = zeros(0,490); r1 = zeros(0,490); rmax = 3*10^-6; rmin = 0*10^-6; r1min = 3*10^-6; r1max = 6*10^-6; for n=1:N; r(n)= ((n-1)*(rmax-rmin))/(N-1)+rmin; r1(n)= ((n-1)*(r1max-r1min))/(N-1)+r1min; end if r<=a psi = (1/besselj(0,1.31689).*(besselj(0,1.31689.*(r/a)))); elseif (r1>=a) psi = (1/besselk(0,0.71819).*(besselk(0,0.71819.*(r1/a)))); end plot((r/a),(1/besselj(0,1.31689).*(besselj(0,1.31689.*(r/a)))),(r1/a),(1/besselk(0,0.71819).*(besselk(0,0.71819.*(r1/a))))); grid on
Please help me. I am very new to matlab. Thanks.

Best Answer

Use logical indexing as described by the blog posts, videos, and documentation that this search on the Support website returns.
a = 1.5;
r = 0:0.01:2;
result = NaN(size(r));
condition1 = r <= a;
result(condition1) = ... % use r(condition1) in place of r in this expression
condition2 = r > a;
result(condition2) = ... % use r(condition2) in place of r in this expression
Now plot using r and result.
Related Question