Chapter 4: Programming in Matlab - College of the Redwoods
Chapter 4: Programming in Matlab - College of the Redwoods
Chapter 4: Programming in Matlab - College of the Redwoods
Create successful ePaper yourself
Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.
276 <strong>Chapter</strong> 4 <strong>Programm<strong>in</strong>g</strong> <strong>in</strong> <strong>Matlab</strong><br />
Test <strong>the</strong> anonymous function. Note that f(5, 3) = √ 5 2 − 3 2 = 4.<br />
>> f(5,3)<br />
ans =<br />
4<br />
That looks correct.<br />
Now, <strong>the</strong> follow<strong>in</strong>g commands produce <strong>the</strong> image <strong>in</strong> Figure 4.4(a). At first<br />
glance, it appears that all is well.<br />
>> [x,y]=meshgrid(l<strong>in</strong>space(-2,2,50));<br />
>> z=f(x,y);<br />
>> mesh(x,y,z)<br />
However, this time <strong>Matlab</strong> ignores <strong>the</strong> imag<strong>in</strong>ary part <strong>of</strong> <strong>the</strong> complex numbers <strong>in</strong><br />
z without even provid<strong>in</strong>g a warn<strong>in</strong>g. This is evident <strong>in</strong> <strong>the</strong> graph <strong>of</strong> z = √ x 2 − y 2<br />
where you see that a large number <strong>of</strong> po<strong>in</strong>ts <strong>in</strong> <strong>the</strong> mesh have z-value equal to<br />
zero. These po<strong>in</strong>ts <strong>in</strong> <strong>the</strong> xy-plane are where <strong>Matlab</strong> is ignor<strong>in</strong>g <strong>the</strong> imag<strong>in</strong>ary<br />
part <strong>of</strong> <strong>the</strong> complex entries <strong>in</strong> z and plott<strong>in</strong>g only <strong>the</strong> real part (which is zero).<br />
We can check to see if <strong>the</strong> matrix z conta<strong>in</strong>s any complex numbers.<br />
>> isreal(z)<br />
ans =<br />
0<br />
The false response <strong>in</strong>dicates <strong>the</strong> presence <strong>of</strong> complex numbers <strong>in</strong> matrix z. We<br />
can replace all <strong>the</strong> complex entries <strong>in</strong> z with <strong>the</strong>se commands.<br />
>> k=real(z)~=z;<br />
>> z(k)=NaN;<br />
You may want to remove <strong>the</strong> suppress<strong>in</strong>g semicolons and view <strong>the</strong> output <strong>of</strong> <strong>the</strong><br />
last two commands.<br />
<strong>Matlab</strong>’s mesh command refuses to plot <strong>the</strong> Nan’s and produces <strong>the</strong> image<br />
<strong>in</strong> Figure 4.4(b).