for i=1:10
x=linspace(0,10,101);
plot(x,sin(x+i));
print(gcf,'-deps',strcat('plot',num2str(i),'.ps'));
end
if
a=3;
if rem(a,2)==0
disp('a is even')
else
disp('a is odd')
end
switch
input_num=1;
switch input_num
case -1
disp('negative 1');
case 0
disp('zero')
case 1
disp('positive 1')
otherwise
disp('other value')
end
while
n=1;
while prod(1:n)<1e100
n=n+1;
end
disp(n);
n=1;
while prod(1:n)<1e100
n=n+1;
end
disp(n);
n=1;
sum=1;
while n<999
sum=sum+n;
n=n+1;
end
disp(sum+n);
for
for n=1:10
a(n)=2^n;
end
disp(a)
for n=1:2:10
a(n)=2^n;
end
disp(a)
Pre-allocating Space to Variables:
tic
A=zeros(2000,2000);
for ii=1:size(A,1)
for jj =1:size(A,2)
A(ii,jj)=ii+jj;
end
end
toc
tic
for ii=1:2000
for jj =1:2000
A(ii,jj)=ii+jj;
end
end
toc
练习题:
A=[1 2;3 4];
for ii=1:size(A,1)
for jj=1:size(A,2)
B(ii,jj)=A(ii,jj);
end
end;
B
A=[0 -1 4;9 -14 25;-34 49 64];
for ii=1:size(A,1)
for jj=1:size(A,2)
if A(ii,jj)<0
A(ii,jj)=-A(ii,jj);
end
end
end;
A
Break:
x=2;
k=0;
error=inf;
error_threshold=1e-32;
while error>error_threshold
if k>100
break;
end
x=x-sin(x)/cos(x);
error=abs(x-pi);
k=k+1;
end
Tips for Script Writing:
Clear all
Close all
;
Ellipsis…
A=[1 2 3 4 5 6;...
6 4 6 3 2 1];
A
Ctrl+c:
Script vs . Fubctions
edit:
User Define Function:
Fuctions with Multiple Inputs and Outputs:
function [a, F]=test02(v2,v1,t2,t1,m)
a=(v2-v1)./(t2-t1);
F=m.*a;
excise:
while true
x=input('please input a F number:');
if isempty(x)
break;
else
y=(x-32)*5/9;
z=[num2str(x),'F is ',num2str(y),'C'];
disp(z);
end
end;
Function Default Variables:
function [volume]=test02(Do,Di,height)
if nargin==2,
height=1;
end
volume=abs(Do.^2-Di.^2)*height*pi/4;
Function Handles:
>> f=@(x) exp(-2*x);
>> x=0:0.1:2;
>> plot(x,f(x));