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.
360 <strong>Chapter</strong> 4 <strong>Programm<strong>in</strong>g</strong> <strong>in</strong> <strong>Matlab</strong><br />
function [m,k]=mymax(v)<br />
m=v(1);<br />
k=1;<br />
for i=1:length(v)<br />
if v(i)>m<br />
m=v(i);<br />
k=i;<br />
end<br />
end<br />
Test it on someth<strong>in</strong>g where you can easily spot <strong>the</strong> maximum, as is <strong>the</strong> case<br />
<strong>in</strong> <strong>the</strong> 5th position <strong>of</strong> <strong>the</strong> follow<strong>in</strong>g vector.<br />
>> v=[2 4 7 8 11 8 4 2 5]<br />
v =<br />
2 4 7 8 11 8 4 2 5<br />
>> [m,i]=mymax(v)<br />
m =<br />
11<br />
i =<br />
5<br />
Now for a comparison. First, mymax.<br />
>> tic, [m,i]=mymax(v); toc<br />
Elapsed time is 0.107614 seconds.<br />
Now us<strong>in</strong>g <strong>Matlab</strong>’s max rout<strong>in</strong>e.<br />
>> tic, [m,i]=max(v); toc<br />
Elapsed time is 0.040215 seconds.