0% found this document useful (0 votes)
154 views69 pages

Matlab Giai Tich

This document contains functions in MATLAB code for analyzing surfaces and calculating integrals. It defines functions for plotting surfaces like paraboloids, ellipsoids, and level curves. It also includes functions for finding critical points and calculating double integrals over surfaces.

Uploaded by

Trần Toàn
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
154 views69 pages

Matlab Giai Tich

This document contains functions in MATLAB code for analyzing surfaces and calculating integrals. It defines functions for plotting surfaces like paraboloids, ellipsoids, and level curves. It also includes functions for finding critical points and calculating double integrals over surfaces.

Uploaded by

Trần Toàn
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 69

GIẢI TÍCH:

NHÓM 1:
function n1b1
% chuong trinh ve parabol elliptic
a=input('nhap so a= ');
b=input('nhap so b= ');
[x,y]=meshgrid(-10:.05:10);
z=x.^2/a+y.^2/b;
% lenh for o duoi de cat got do thi cho dep mat :)
for i=1:length(x)
for j=1:length(x)
if z(i,j)> 10^2/a || z(i,j) > 10^2/b
z(i,j)=NaN;x(i,j)=NaN;y(i,j)=NaN;
end
end
end
set(surf(x,y,z),'facecolor','b','edgecolor','non','facealpha',.3); % ve do thi
rotate3d on
end

function n1b2
syms x y
u=input('nhap ham u(x,y)= ');
disp(['dao ham rieng theo x cap 10 tai (1,2) la: ' num2str(subs(diff(u,10,x) ,[x y],[1
2]))])
%lenh diff la dao ham
% lenh subs la thay x va y bang so x0 va y0
end

function n1b3
clc
syms x y real
f=input('nhap ham f(x,y)= ');
[a b]=solve([char(diff(f,'x')) '=0'],[char(diff(f,'y')) '=0']); % giai dao ham cap 1
a=double(a);
b=double(b);
% tinh dao ham cap 2
A=diff(f,2,x);
B=diff(f,x);B=diff(B,y);
C=diff(f,2,y);

cd=zeros(0); ct=zeros(0);
zcd=zeros(0); zct=zeros(0);
n=size(a,1);i=1;
while i<=n;
x=a(i);y=b(i);
sA=eval(A);sB=eval(B);sC=eval(C); %tim A,B,C
delta=(sA*sC-sB^2); %tinh delta
delta=double(delta);
if delta > 0
if sA > 0 % A > 0 la cuc tieu
ct=[ct;a(i) b(i)]; zct=[zct;eval(f)];
i=i+1;
elseif sA < 0 % A > 0 la cuc dai
cd=[cd;a(i) b(i)]; zcd=[zcd;eval(f)];
i=1+i;
else
a(i)=[];b(i)=[];
n=n-1;
end
else
a(i)=[];b(i)=[];
n=n-1;
end
end
if size([zcd;zct],1)>= 2 % ve hinh voi 2 cuc tri tro len
[x,y]=meshgrid(min(a)-abs(max( a )-min(a))/5:.1:max(a)+abs(max(a)-min(a))/5,min(b)-
abs(max(b)-min(b))/5:.1:max(b)+abs(max(b)-min(b))/5);
f=char(f);f=strrep(f,'^','.^');f=strrep(f,'*','.*');f=eval(f);
[x y f]=khu(x,y,f);
set(surf(x,y,f),'facecolor','b','edgecolor','non','facealpha',.3)
hold on
ctri(cd,ct,zcd,zct)
elseif size([zcd;zct],1)== 1 % ve hinh voi 1 cuc tri
[x,y]=meshgrid(a-2:.1:a+2,b-2:.1:b+2);
f=char(f);f=strrep(f,'^','.^');f=strrep(f,'*','.*');f=eval(f);
[x y f]=khu(x,y,f);
set(surf(x,y,f),'facecolor','b','edgecolor','non','facealpha',.3)
hold on
ctri(cd,ct,zcd,zct)
else % khong co cuc tri
disp('f khong co cuc tri chat, con co cuc tri ko chat hay khong thi chiu :))' )
[x,y]=meshgrid(-2:.1:2);
f=char(f);f=strrep(f,'^','.^');f=strrep(f,'*','.*');f=eval(f);
[x y f]=khu(x,y,f);
set(surf(x,y,f),'facecolor','b','edgecolor','non','facealpha',.3)
end
rotate3d on
hold off
xlabel('truc x')
ylabel('truc y')
zlabel('truc z')
end

function ctri(cd,ct,zcd,zct) % chuong trinh ve cuc tri


cd=double(cd);zcd=double(zcd);
for i=1:size(zcd,1)
disp([' f co cuc dai chat: ' '(' num2str(cd(i,1)) ',' num2str(cd(i,2)) ','
num2str(zcd(i)) ')'])
[x,y]=meshgrid(cd(i,1)-0.2:.05:cd(i,1)+0.2,cd(i,2)-0.2:.05:cd(i,2)+0.2);
z=zcd(i)+x.*0+y.*0;
set(surf(x,y,z),'facecolor','r','edgecolor','non')
text(cd(i,1),cd(i,2),zcd(i)+.1,['cuc dai (' num2str(cd(i,1)) ',' num2str(cd(i,2)) ','
num2str(zcd(i)) ')'])
end
ct=double(ct);zct=double(zct);
for i=1:size(zct,1)
disp([' f co cuc tieu chat: ' '(' num2str(ct(i,1)) ',' num2str(ct(i,2)) ','
num2str(zct(i)) ')'])
[x,y]=meshgrid(ct(i,1)-0.2:.05:ct(i,1)+0.2,ct(i,2)-0.2:.05:ct(i,2)+0.2);
z=zct(i)+x.*0+y.*0;
set(surf(x,y,z),'facecolor','r','edgecolor','non')
text(ct(i,1),ct(i,2),zct(i)-.1,['cuc tieu (' num2str(ct(i,1)) ',' num2str(ct(i,2)) ','
num2str(zct(i)) ')'])
end
end

function [x y f]=khu(x,y,f) % chuong trinh loai bo cac diem khong ton tai cua ham f
for i=1:length(x)
for j=1:length(y)
if ~isreal(f(i,j))
f(i,j)=NaN;x(i,j)=NaN;y(i,j)=NaN;
end
end
end
end

function n1b5
[x,y]=meshgrid(-sqrt(3):.05:sqrt(3)); % tao luoi
z=sqrt(4-x.^2-y.^2); % mat tren
z2=-sqrt(4-x.^2-y.^2)+2; % mat duoi
for i=1:length(x) % vong lap loai bo cac diem nam ngoai mien giao nhau
for j=1:length(x)
if x(i,j)^2+y(i,j)^2 > 3
x(i,j)=NaN;y(i,j)=NaN;
z(i,j)=NaN;
z2(i,j)=NaN;
end
end
end
set(surf(x,y,z),'facecolor','b','edgecolor','non','facealpha',.3) %ve mat tren
hold on
set(surf(x,y,z2),'facecolor','b','edgecolor','non','facealpha',.3) % ve mat duoi
pcolor(x,y,z2) % ve hinh chieu
hold off
rotate3d on
syms x y phi r real
z=sqrt(4-x^2-y^2); z2=-sqrt(4-x^2-y^2)+2;
x=2*r*cos(phi);y=2*r*sin(phi); % dat x,y theo toa do truc
z=eval(z);z2=eval(z2); % cap nhat bien moi cho x va y
V=int(int(4*r*(z-z2),'r',0,sqrt(3/4)),'phi',0,2*pi); %tinh tich phan kep
V=double(V);
disp(['the tich can tinh la: ' num2str(V)])
end

function n1b6
syms x y real
f=input('nhap ham f(x,y)= ');
x=sqrt(1-y^2)+1;
g=eval(f); %thay x vao f
g=g*sqrt(1+diff(x,'y')^2); % tinh tich phan duong loai 1
l=int(g,'y',-1,1); % tinh tich phan
l=double(l);
t=-pi/2:.1:pi/2;
x=1+cos(t);y=sin(t); % dat x,y theo toa do truc
z=0+0*x;
plot3(x,y,z) % ve duong
disp(['tich phan I= ' num2str(l)])
end

function n1b7
clc
[x,y]=meshgrid(-1:.02:1);
z=y.^2;
for i=1:length(x) % loai cac diem bat dinh
for j=1:length(x)
if x(i,j)^2+y(i,j)^2 > 1 % loai cac diem nam ngoai hinh tru
x(i,j)=NaN;
y(i,j)=NaN;
z(i,j)=NaN;
end
end
end
set(surf(x,y,z),'facecolor','b','edgecolor','non','facealpha',.3) % ve mat trong giao tuyen
hold on
% ve duong giao tuyen
t=linspace(0,2*pi,50);
x=cos(t);y=sin(t);z=y.^2;
plot3(x,y,z,'color','g')
%tinh tich phan mat
syms x y z real
P=x+y;
Q=2*x-z;
R=y;
f=z-y^2;
n=[diff(f,'x') diff(f,'y') diff(f,'z')];
n=n/sqrt(diff(f,'x')^2 + diff(f,'y')^2 + diff(f,'z')^2); % tinh vector don vi cua vector
phap
%phuong phap tinh la phuong phap stokes

p=(diff(R,'y')-diff(Q,'z'))*n(1,1);
q=(diff(P,'z')-diff(R,'x'))*n(1,2);
r=(diff(Q,'x')-diff(P,'y'))*n(1,3);

z=y^2;
f=(eval(p)+eval(q)+eval(r))*sqrt(1+diff(z,'x')^2+diff(z,'y')^2);
% da chuyen ve tich phan mat loai 1
syms r phi real
x=r*cos(phi);y=r*sin(phi); % chuyen sang phuong phap truc toa do
f=eval(f);
S=int(int(f*r,'r',0,1),'phi',0,2*pi); %tinh tich phan
S=double(S);
disp(['Tich phan can tinh la: I= ' num2str(S)])
% ve vector phap tai M0

disp('nhap diem M0 thuoc mat z=y^2 va x^2+y^2 <= 1 ')


disp('vidu M(0,1,1), thi ta nhap: 0,1,1')
m=input('M0= ','s');
m=str2num(m);
x=m(1,1);y=m(1,2);z=m(1,3);
n=eval(n);% the toa do diem vao vector

title(['mat z=y^2 nam trong hinh tru x^2+y^2=1 ' 'Va phap vector tai diem M0(' num2str(x)
',' num2str(y) ',' num2str(z) ')']) % tao tieu de

%bat dau ve vector phap


t=linspace(0,1,20);
x=n(1,1)*t+x;
y=n(1,2)*t+y;
z=n(1,3)*t+z;
plot3(x,y,z,'color','r')
hold off
rotate3d on
% OK men :))
End

NHÓM 2:
function n2b1
% ve mat ellipsoid
% co nhieu cach ve. ban co the dung ham tu viet de ve
% nhung o day toi se ve bang ham thu viet cua matlab rat don gian
a=input('nhap a= ');
b=input('nhap b= ');
c=input('nhap c= ');
ellipsoid(0,0,0,a,b,c);
rotate3d on
%trong do: 0,0,0 la toa do tam
% a,b,c lan luoc la ban kinh truc Ox, Oy, Oz
end

function n2b2
syms x y z real
f=input('nhap ham z(x,y)= ');
disp('nhap lan luoc toa do M0 thuoc z(x,y)')
x0=input('x0= ');y0=input('y0= ');z0=input('z0= ');

f1=f-z; %chuyen thanh f(x,y,z)=0

n=[ diff(f1,'x') diff(f1,'y') diff(f1,'z')]; %tinh dao ham


n1=subs(n,[x y z],[x0 y0 z0]); n1=double(n1); %tim vector gradian
f1=n1(1,1)*(x-x0)+n1(1,2)*(y-y0)+n1(1,3)*(z-z0); %mat tiep tuyen
disp(['phuonh trinh mat tiep tuyen la: ' char(f1) ' = 0' ])
disp('phuong trinh phap tuyen la: ')

% ve duong thang phap tuyen


t=linspace(2,-2,20);
x1=n1(1,1).*t+x0;
y1=n1(1,2).*t+y0;z1=n1(1,3).*t+z0;
plot3(x1,y1,z1,'color','r')
hold on

%hien thi phuong trinh duong thang phap tuyen


syms t real
x1=n1(1,1)*t+x0;y1=n1(1,2)*t+y0;z1=n1(1,3)*t+z0;
disp(['x= ' char(x1)])
disp(['y= ' char(y1)])
disp(['z= ' char(z1)])

%ve do thi z(x,y)


[x,y]=meshgrid(x0-5:.05:x0+5,y0-5:.05:y0+5);
f=char(f);f=strrep(f,'*','.*');f=strrep(f,'^','.^');
f=eval(f);
[x y f]=loai(x,y,f); %loai bo cac diem bat dinh
set(surf(x,y,f),'facecolor','b','edgecolor','non','facealpha',.3)

%ve mat tiep tuyen


[x,y]=meshgrid(x0-2:.1:x0+2,y0-2:.1:y0+2);
z=(z0*n1(1,3)-(n1(1,1)*(x-x0)+n1(1,2)*(y-y0)))/n1(1,3);
[x y z]=loai(x,y,z);
set(surf(x,y,z),'facecolor','g','edgecolor','non','facealpha',.3)
hold off
rotate3d on
xlabel('x')
ylabel('y')
zlabel('z')
end
%ham loai bo cac diem bat dinh
function [x y z]=loai(x,y,z)
for i=1:length(x)
for j=1:length(y)
if ~isreal(z(i,j))
z(i,j)=NaN;x(i,j)=NaN;y(i,j)=NaN;
end
end
end
end

function n2b3
clc
syms x y lamda real
f=input('nhap ham f(x,y)= ');
disp('nhap a b cua ellip x^2/a+y^2/b=1')
a=input('nhap a= ');
b=input('nhap b= ');
phi=x^2/a+y^2/b-1;
%ve hinh
t=linspace(0,2*pi,40);
[x,y]=meshgrid(cos(t)*sqrt(a),sin(t)*sqrt(b));
z=[char(f) '+0*x'];z=strrep(z,'*','.*');z=strrep(z,'^','.^');
z=eval(z);
[x y z]=khu(x,y,z);
set(surf(x,y,z),'facecolor','b','edgecolor','non','facealpha',.2)
hold on
x=cos(t)*sqrt(a);
y=sin(t)*sqrt(b);
z=eval(f);
plot3(x,y,z,'color','r')

%tim cuc tri


L=f+lamda*(phi);
Lx=diff(L,'x');
Ly=diff(L,'y');
[l m n]=solve(Lx,Ly,phi,'x','y','lamda');%giai he dao ham cap 1 voi: l <=> lamda , m <=> x ,
n <=> y.
m=double(m); m(abs(imag(m))>0.0000000001)=inf;m=m-imag(m)*1i; %loai so phuc
n=double(n); n(abs(imag(n))>0.0000000001)=inf;n=n-imag(n)*1i;
l=double(l); l(abs(imag(l))>0.0000000001)=inf;l=l-imag(l)*1i;
Lxx=diff(Lx,'x');Lyy=diff(Ly,'y');Lxy=diff(Lx,'y'); %dao ham cap 2
phix=diff(phi,'x');phiy=diff(phi,'y'); %dao ham dieu kien
for i=1:length(m) %xet cuc dai, cuc tieu
if m(i)==inf || n(i)==inf || l(i)==inf
continue
end
x=m(i);
y=n(i);
lamda=l(i);
dphi=-eval(phix)/eval(phiy);
A=eval(Lxx);B=eval(Lxy);C=eval(Lyy);
dL=A+B*dphi+C*dphi^2;
z=eval(f);
if (dL > 0 && isreal(m(i))) || ((dphi==inf || dphi==-inf) && C>0)%dao ham cap 2 > 0 =>
cuc tieu
disp([' diem (' num2str(m(i)) ',' num2str(n(i)) ',' num2str(z) ') la diem cuc
tieu'])
text(x,y,z-.2,['cuc tieu (' num2str(m(i)) ',' num2str(n(i)) ',' num2str(z) ')' ])
elseif (dL < 0 && isreal(m(i))) || ((dphi==inf || dphi==-inf) && C<0) %dao ham cap 2 < 0
=> cuc dai
disp([' diem (' num2str(m(i)) ',' num2str(n(i)) ',' num2str(z) ') la diem cuc dai'])
text(x,y,z+.2,['cuc dai (' num2str(m(i)) ',' num2str(n(i)) ',' num2str(z) ')' ])
end
end
hold off
rotate3d on
end
%loai cac diem bat dinh
function [x y f]=khu(x,y,f) % chuong trinh loai bo cac diem khong ton tai cua ham f
for i=1:length(x)
for j=1:length(y)
if ~isreal(f(i,j))
f(i,j)=NaN;x(i,j)=NaN;y(i,j)=NaN;
end
end
end
end
function n2b4
syms x y real
warning off
y1=input('nhap ham y1(x)= ');
y2=input('nhap ham y2(x)= ');
f=input('nhap ham tinh tich phan f(x,y)= ');
n=solve(y1-y2);
n=unique(n);
if length(n)~=2
disp('2 ham y1 va y2 khong cat nhau tai 2 diem phan biet')
return
end
if double(subs((y1-y2),'x',(n(1)+n(2))/2)) > 0 % neu y1 nam tren y2
I=int(int(f,'y',y2,y1),'x',n(1),n(2));
else % neu y2 nam tren y1
I=int(int(f,'y',y1,y2),'x',n(1),n(2));
end
I=double(I);
disp(['tich phan can tinh I= ' num2str(I)])
end

function n2b5
clc
[x,y]=meshgrid(-2:.01:2);
z=sqrt(4-x.^2-y.^2);
z1=sqrt(1-x.^2-y.^2);
z2=sqrt(x.^2+y.^2);
for i=1:length(x)
for j=1:length(x)
if x(i,j)^2+y(i,j)^2 > 2
z(i,j)=NaN;z1(i,j)=NaN;z2(i,j)=NaN;
end
if x(i,j)^2+y(i,j)^2 > 1/2
z1(i,j)=NaN;
end
if x(i,j)^2+y(i,j)^2 < 1/2
z2(i,j)=NaN;
end
end
end
set(surf(x,y,z),'facecolor','b','edgecolor','non','facealpha',.3)
hold on
set(surf(x,y,z1),'facecolor','b','edgecolor','non','facealpha',.3)
set(surf(x,y,z2),'facecolor','b','edgecolor','non','facealpha',.3)
hold off
rotate3d on
syms x y t r real
z=sqrt(4-x^2-y^2);
z1=sqrt(1-x^2-y^2);
z2=sqrt(x^2+y^2);
x=r*cos(t);y=r*sin(t);
z=eval(z);z1=eval(z1);z2=eval(z2);
V=int(int((z-z2)*r,'r',1/sqrt(2),sqrt(2)),'t',0,2*pi);
V=V+int(int((z-z1)*r,'r',0,1/sqrt(2)),'t',0,2*pi);
V=double(V);
disp(['the tich vat the la V= ' num2str(V)])
end

function n2b6
warning off
x=linspace(-2,2,40);
y=sqrt(4-x.^2);
z=4-x;
plot3(x,y,z)
hold on
y=-sqrt(4-x.^2);
plot3(x,y,z)
hold off
rotate3d on
syms x y z t real
f=input('nhap ham f(x,y,z)= ');
x=2*cos(t);
y=2*sin(t);
z=4-2*cos(t);
d=sqrt(diff(x,'t')^2+diff(y,'t')^2+diff(z,'t')^2);
L=int(eval(f)*d,'t',0,2*pi);
L=double(L);
if L <0.0000000000000000000000001
L=0;
end
disp(['tich phan L= ' num2str(L)])
end

function n2b7
clc
t=linspace(0,2*pi,50);
[x,y]=meshgrid(sqrt(3)*cos(t)-1,sqrt(3)*sin(t));
z=x.^2+y.^2;
set(surf(x,y,z),'facecolor','b','edgecolor','non','facealpha',.1)
hold on
z=2-2.*x;
set(surf(x,y,z),'facecolor','g','edgecolor','non','facealpha',.1)
% ve duong giao tuyen
t=linspace(0,2*pi,50);
x=sqrt(3)*cos(t)-1;y=sqrt(3)*sin(t);z=x.^2+y.^2;
plot3(x,y,z,'color','r')
%tinh tich phan mat
syms x y z real
P=3*x-+y^2;
Q=3*y-z^2;
R=3*z-x^2;
f=z+2*x-2;
n=[diff(f,'x') diff(f,'y') diff(f,'z')];
n=n/sqrt(diff(f,'x')^2 + diff(f,'y')^2 + diff(f,'z')^2); % tinh vector don vi cua vector
phap
%phuong phap tinh la phuong phap stokes

p=(diff(R,'y')-diff(Q,'z'))*n(1,1);
q=(diff(P,'z')-diff(R,'x'))*n(1,2);
r=(diff(Q,'x')-diff(P,'y'))*n(1,3);

z=2-2*x;
% chuyen ve tich phan mat loai 1
f=(eval(p)+eval(q)+eval(r))*sqrt(1+diff(z,'x')^2+diff(z,'y')^2);
%tinh tich phan
syms r phi real
x=r*cos(phi);y=r*sin(phi); % chuyen sang phuong phap truc toa do
f=eval(f);
S=int(int(f*r,'r',0,sqrt(3)),'phi',0,2*pi); %tinh tich phan
S=double(S);
disp(['Tich phan can tinh la: I= ' num2str(S)])
% ve vector phap tai M0

disp('nhap diem M0 thuoc mat 2*x+z=2 va z >= x^2+y^2 ')


disp('vidu M(0,-1,2), thi ta nhap: 0,-1,2')
m=input('M0= ','s');
m=str2num(m);
x=m(1,1);y=m(1,2);z=m(1,3);
n=eval(n);% the toa do diem vao vector

title(['mat z=y^2 nam trong hinh tru x^2+y^2=1 ' 'Va phap vector tai diem M0(' num2str(x)
',' num2str(y) ',' num2str(z) ')']) % tao tieu de

%bat dau ve vector phap


t=linspace(0,1,20);
x=n(1,1)*t+x;
y=n(1,2)*t+y;
z=n(1,3)*t+z;
plot3(x,y,z,'color','r')
hold off
rotate3d on
% OK men :))
end

NHÓM 3:
function n3b1
disp('nhap a b thuoc z=x^2/a^2-y^2/b^2')
a=input('nhap a= ');
b=input('nhap b= ');
c=[abs(a) abs(b)]; c=max(c);
[x,y]=meshgrid(-c:.1:c);
z=x.^2/a.^2-y.^2/b.^2;
set(surf(x,y,z),'facecolor','b','edgecolor','non','facealpha',.3)
end

function n3b2
syms x y u real
f=input('nhap ham f(u)= ');
u=input('nhap ham u(x,y)= ');
disp('phap lan luoc cac toa do cua M0:')
x0=input('x0= ');
y0=input('y0= ');
f=eval(f); %thay u(x,y) vao f(u)
c=subs(f,[x y],[x0 y0]); %tinh f tai M0
c=double(c);
%tinh dao ham
x=x0;y=y0;
fx=diff(f,'x');a=eval(fx);
fy=diff(f,'y');b=eval(fy);
%xuat f'x va f'y
disp(['f`x= ' num2str(a)])
disp(['f`y= ' num2str(b)])
%ve do thi
[x,y]=meshgrid(x0-2:.1:x0+2,y0-2:.1:y0+2);
f=char(f);f=strrep(f,'^','.^');f=strrep(f,'*','.*');
f=eval(f);
[x y f]=khu(x,y,f);
set(surf(x,y,f),'facecolor','b','edgecolor','non','facealpha',.3)
hold on
t=linspace(-2,2,40);
x=x0+t;
y=y0+0*t;
z=c+a*t;
plot3(x,y,z,'r','linewidth',2)
x=x0+0*t;
y=y0+t;
z=c+b*t;
plot3(x,y,z,'r','linewidth',2)
text(x0,y0,c+.2,['M0 (' num2str(x0) ',' num2str(y0) ',' num2str(a) ')'])
hold off
rotate3d on
end

function [x y f]=khu(x,y,f) % chuong trinh loai bo cac diem khong ton tai cua ham f
f=double(f);
for i=1:length(x)
for j=1:length(y)
if ~isreal(f(i,j))
f(i,j)=NaN;x(i,j)=NaN;y(i,j)=NaN;
end
end
end
end

function n3b3
warning off
syms x y lamda real
f=input('nhap ham f(x,y)= ');
disp('nhap parabol y(x). vd: y=6+4*x^2 ')
phi=input('y = ');
hold on
L=f+lamda*(phi-y);
Lx=diff(L,'x');
Ly=diff(L,'y');
[l m n]=solve(Lx,Ly,phi-y,'x','y','lamda');
%giai he dao ham cap 1 voi: l <=> lamda , m <=> x , n <=> y.
m=double(m); m(abs(imag(m))>0.0000000001)=inf;m=m-imag(m)*1i; %loai so phuc
n=double(n); n(abs(imag(n))>0.0000000001)=inf;n=n-imag(n)*1i;
l=double(l); l(abs(imag(l))>0.0000000001)=inf;l=l-imag(l)*1i;
Lxx=diff(Lx,'x');Lyy=diff(Ly,'y');Lxy=diff(Lx,'y'); %dao ham cap 2
phix=diff(phi-y,'x');phiy=diff(phi-y,'y'); %dao ham dieu kien
k=0;
for i=1:length(m) %xet cuc dai, cuc tieu
if m(i)==inf || n(i)==inf || l(i)==inf
continue
end
x=m(i);y=n(i);lamda=l(i);
dphi=-eval(phix)/eval(phiy);
A=eval(Lxx);B=eval(Lxy);C=eval(Lyy);
dL=A+B*dphi+C*dphi^2;
z=eval(f);
if (dL > 0 && isreal(m(i))) || ((dphi==inf || dphi==-inf) && C>0) %dao ham cap 2 > 0 =>
cuc tieu
k=k+1;
disp([' diem (' num2str(m(i)) ',' num2str(n(i)) ',' num2str(z) ') la diem cuc
tieu'])
text(x,y,z-1,['cuc tieu (' num2str(m(i)) ',' num2str(n(i)) ',' num2str(z) ')' ])
elseif (dL < 0 && isreal(m(i))) || ((dphi==inf || dphi==-inf) && C<0) %dao ham cap 2 < 0
=> cuc dai
k=k+1;
disp([' diem (' num2str(m(i)) ',' num2str(n(i)) ',' num2str(z) ') la diem cuc dai'])
text(x,y,z+1,['cuc dai (' num2str(m(i)) ',' num2str(n(i)) ',' num2str(z) ')' ])
end
end
%ve do thi
if k~=0
x=linspace(min(m)-2,max(m)+2,20);
y=eval(phi);
[x,y]=meshgrid(x,y);
z=char(f);z=strrep(z,'*','.*');z=strrep(z,'^','.^');
z=eval(f);
[x y z]=khu(x,y,z);
set(surf(x,y,z),'facecolor','b','edgecolor','non','facealpha',.2)
x=linspace(min(m)-2,max(m)+2,20);
y=eval(phi);
z=eval(f);
plot3(x,y,z,'color','r')
else
disp('ham da cho ko co cuc tri dieu kien')
x=linspace(-2,2,20);
y=eval(phi);
[x,y]=meshgrid(x,y);
z=char(f);z=strrep(z,'*','.*');z=strrep(z,'^','.^');
z=eval(f);
[x y z]=khu(x,y,z);
set(surf(x,y,z),'facecolor','b','edgecolor','non','facealpha',.2)
hold on
x=linspace(-2,2,20);
y=eval(phi);
z=eval(f);
plot3(x,y,z,'color','r')
end
hold off
rotate3d on
end
%loai cac diem bat dinh
function [x y f]=khu(x,y,f) % chuong trinh loai bo cac diem khong ton tai cua ham f
for i=1:length(x)
for j=1:length(y)
if ~isreal(f(i,j))
f(i,j)=NaN;x(i,j)=NaN;y(i,j)=NaN;
end
end
end
end

function n3b4
syms x y real
warning off
x1=input('nhap ham x1(y)= ');
x2=input('nhap ham x2(y)= ');
f=input('nhap ham tinh tich phan f(x,y)= ');
n=solve(x1-x2);
n=unique(n);
n=double(n);
if length(n)~=2
disp('2 ham x1 va x2 khong cat nhau tai 2 diem phan biet')
return
end
if double(subs((x1-x2),'y',(n(1)+n(2))/2)) > 0 % neu x1 nam ben phai x2
I=int(int(f,'x',x2,x1),'y',n(1),n(2));
ve(x1,x2,n(1),n(2))
else % neu x2 nam ben phai x1
I=int(int(f,'x',x1,x2),'y',n(1),n(2));
ve(x2,x1,n(1),n(2))
end
I=double(I);
disp(['tich phan can tinh I= ' num2str(I)])
end

function ve(x1,x2,a,b)
x1=sym(x1);x1=[char(x1) '+0*y'];
x2=sym(x2);x2=[char(x2) '+0*y'];
y=linspace(a,b,25);
x1=strrep(x1,'^','.^');x1=strrep(x1,'*','.*');
xa=eval(x1);
ya=y;
y=linspace(b,a,25);
x2=strrep(x2,'^','.^');x2=strrep(x2,'*','.*');
x=eval(x2);
xa=[xa x];
ya=[ya y];
fill(xa,ya,'r')
grid on
end

function n3b5
clc
syms x y z real
f=input('nhap ham f(x,y,z)= ');
f=sym(f);
[x, y, ~] = ellipsoid(0,0,1,1,1,1);
z=1+0.*x;
z1=-sqrt(1-(x.^2+y.^2))+1;
set(surf(x,y,z),'facecolor','g','edgecolor','non','facealpha',.1)
hold on
set(surf(x,y,z1),'facecolor','b','edgecolor','non','facealpha',.1)
hold off
rotate3d on
syms theta phi p
x=p*cos(phi)*sin(theta);
y=p*sin(phi)*sin(theta);
z=1+p*cos(theta);
f=eval(f);
I=int(int(int(f*p^2*sin(theta),'p',0,1),'phi',0,2*pi),'theta',pi/2,pi);
I=double(I);
disp(['tich phan can tinh la I= ' num2str(I)])
end

function n3b6
clc
warning off
%ve hinh
[x,y]=meshgrid(-2:.1:2);
z=-x-y;
set(surf(x,y,z),'facecolor','g','edgecolor','non','facealpha',.3)
hold on
[x, y, z] = ellipsoid(0,0,0,2,2,2,30);
set(surf(x,y,z),'facecolor','b','edgecolor','non','facealpha',.3)
%ve giao tuyen
x=linspace(-2*sqrt(2/3),2*sqrt(2/3),40);
y=-x/2-sqrt(-3.*x.^2+8)/2;
z=-x-y;
plot3(x,y,z,'r');
y=-x/2+sqrt(-3.*x.^2+8)/2;
z=-x-y;
plot3(x,y,z,'r');
hold off
rotate3d on
%tinh tich phan
syms x y z t real
f=input('nhap f(x,y)= ');
f=sym(f);
x=t;
y=-x/2+sqrt(-3.*x.^2+8)/2;
z=-x-y;
h=eval(f);
g=sqrt(1+diff(y,'t')^2+diff(z,'t')^2);
I=int(h*g,'t',-2*sqrt(2/3),2*sqrt(2/3));
y=-x/2+sqrt(-3.*x.^2+8)/2;
z=-x-y;
h=eval(f);
I=I+int(h*g,'t',-2*sqrt(2/3),2*sqrt(2/3));
if ~isreal(I)
disp('Matlab xin botay.com, tich phan cua ban qua kho :P')
else
I=double(I);
disp(['tich phan can tinh la I= ' num2str(I)])
end
end

function n3b7
clc
disp('nhap lan luoc cac toa do cua M0 thuoc mat cong y^2+x^2+z^2=4 :')
x0=input('x0= ');
y0=input('y0= ');
z0=input('z0= ');
syms x y z real
syms t phi p real
P=y+z;
Q=x-z;
R=z+1;
f=z^2+y^2+x^2-4;
n=[diff(f,'x') diff(f,'y') diff(f,'z')];
g=diff(P,'x')+diff(Q,'y')+diff(R,'z');
x=p*cos(phi)*sin(t);
y=p*sin(t)*sin(phi);
z=p*cos(t);
g=eval(g);
V=int(int(int(g*p^2*sin(t),'p',0,2),'t',0,pi/2),'phi',0,2*pi);
% ta tru cho tich phan mat duoi. mat duoi huong xuong oz => V=V+S
V=V+4*pi;
V=double(V);
disp(['tich phan can tinh la V= ' num2str(V) ])
%ve hinh
[x, y, ~] = ellipsoid(0,0,0,2,2,2,100); % tao luoi
z=sqrt(4-x.^2-y.^2);
z(imag(z)>0)=0;
set(surf(x,y,z),'facecolor','b','edgecolor','non','facealpha',.3)
hold on
% ve vector phap tai M0
x=x0;y=y0;z=z0;
n=eval(n);% the toa do diem vao vector
%bat dau ve vector phap
t=linspace(0,1,20);
x=n(1,1)*t+x;
y=n(1,2)*t+y;
z=n(1,3)*t+z;
plot3(x,y,z,'color','r')
hold off
rotate3d on
axis([-3 3 -3 3 -1 3])
disp('duong mau do la vector phap tuyen :)')
% OK men :))
end

NHÓM 4:
function n4b1
disp('ban mun ve Hyperboloid 1 tang hay 2 tang')
disp('neu mun ve 1 tang thi nhap: 1')
d=input('1 hay 2: ','s');d=str2double(d);
if d==1
d=-1;
disp('nhap cac so a b c thuoc x^2/a^2+y^2/b^2-z^2/c^2=1')
disp('nen nhap cac so nho hon 5')
elseif d==2
d=1;
disp('nhap cac so a b c thuoc x^2/a^2+y^2/b^2-z^2/c^2=-1')
disp('nen nhap cac so nho hon 5')
else
return
end
a=input('a= ');A=1/a^2;
b=input('b= ');B=1/b^2;
c=input('c= ');C=-1/c^2;
theta = linspace(-pi/2,pi/2,100);
phi = linspace(0,2*pi(),100);
[p,t] = meshgrid(phi,theta);
for i=1:100
for j=1:100
aa(i,j) =
A*((cos(p(i,j))*cos(t(i,j)))^2)+B*((sin(p(i,j))*cos(t(i,j)))^2)+C*(sin(t(i,j))^2);
delta(i,j) = -4*d*aa(i,j);
if delta(i,j)<0
R(i,j)=NaN;
else
R(i,j) =sqrt(delta(i,j))/(2*aa(i,j));
end
X(i,j) = R(i,j)*cos(p(i,j))*cos(t(i,j));
Y(i,j) = R(i,j)*sin(p(i,j))*cos(t(i,j));
Z(i,j) = R(i,j)*sin(t(i,j));
end
end
for i=1:100
for j=1:100
if abs(X(i,j))>5
X(i,j)=NaN;
end
if abs(Y(i,j))>5
Y(i,j)=NaN;
end
if abs(Z(i,j))>5
Z(i,j)=NaN;
end
end
end
surf(X,Y,Z)
rotate3d on
end

function n4b3
syms x y lamda real
f=input('nhap ham f(x,y)= ');f=sym(f);
disp(' nhap toa do I(x0,y0) va R :')
x0=input('x0= ');
y0=input('y0= ');
r=input('R= ');
%tim cuc tri trong mien D
[p q]=solve(diff(f,'x'),diff(f,'y'));
[p q]=loai(p,q);
p=double(p);q=double(q);
A=[];
for i=1:length(p)
if (p(i)-x0)^2+(q(i)-y0)^2 < r^2
A(i,2)=p(i);
A(i,3)=q(i);
A(i,1)=subs(f,[x y],[p(i) q(i)]);
end
end
if isempty(A)
k=0;
else
k=size(A,1);
end
%tim cuc tri tren duong D
phi=(x-x0)^2+(y-y0)^2-r^2;
L=f+lamda*(phi);
Lx=diff(L,'x');
Ly=diff(L,'y');
[l m n]=solve(Lx,Ly,phi,'x','y','lamda');%giai he dao ham cap 1 voi: l <=> lamda , m <=> x ,
n <=> y.
[m n]=loai(m,n);
m=double(m);n=double(n);l=double(l); %chuyen sang dang double
for i=1:length(m)
A(i+k,2)=m(i);
A(i+k,3)=n(i);
A(i+k,1)=subs(f,[x y],[m(i) n(i)]);
end
%ve do thi
[x,y]=meshgrid(x0-r:.1:x0+r,y0-r:.1:y0+r);
z=[char(f) '+0.*x'];z=strrep(z,'^','.^');z=strrep(z,'*','.*');
z=eval(z);
z(~isreal(z))=NaN;
set(surf(x,y,z),'facecolor','b','edgecolor','non','facealpha',.3)
hold on
t=linspace(0,2*pi,50);
x=r*cos(t)+x0;
y=r*sin(t)+y0;
z=[char(f) '+0.*x'];
z=eval(f);
if size(z,2)~=size(x,2)
z=x;
z(:,:)=double(f);
end
plot3(x,y,z,'r')

if isempty(A)
disp('khong co GTLN va GTNN')
return
end

a=max(A(:,1));
b=min(A(:,1));
if a==b
if a>subs(f,[x y],[x0+0.12 y0+0.12])
disp(['GTLN f(' num2str(A(1,2)) ',' num2str(A(1,3)) ')= ' num2str(A(1,1))])
else
disp(['GTNN f(' num2str(A(1,2)) ',' num2str(A(1,3)) ')= ' num2str(A(1,1))])
end
return
end
GTLN='GTLN la ';
GTNN='GTNN la f(';

for i=1:size(A)
if A(i,1)==a
GTLN=[GTLN 'f(' num2str(A(i,2)) ',' num2str(A(i,3)) ')= '];
text(A(i,2),A(i,3),a+1,['(' num2str(A(i,2)) ',' num2str(A(i,3)) ',' num2str(a)
')' ])
elseif A(i,1)==b
GTNN=[GTNN 'f(' num2str(A(i,2)) ',' num2str(A(i,3)) ')= '];
text(A(i,2),A(i,3),b-1,['(' num2str(A(i,2)) ',' num2str(A(i,3)) ',' num2str(b)
')' ])
end
end
GTLN=[GTLN num2str(a)];
GTNN=[GTNN num2str(b)];
disp(GTLN)
disp(GTNN)
hold off
rotate3d on
end

function [a b]=loai(a,b)
for i=1:length(a)
if ~isreal(a(i)) || ~isreal(b(i))
a(i,:)=[];
b(i,:)=[];
end
end
end

function n4b4
clc
warning off
syms x y real
f=input('nhap f(x,y)= ');
y1=input('nhap y1= ');
y2=input('nhap y2= ');
disp('nhap khoang [a,b]')
a=input('a= ');b=input('b= ');
if a>=b
disp('nhap sai a b')
return
end
m=solve(y1-y2);
m=double(m);
m=m(m>a);m=m(m<b);
if ~isempty(m)
disp('y1,y2 cat nhau trong khoang [a,b[')
return
end
I=int(int(f,'y',y2,y1),'x',a,b);
I=double(I);
if subs(y1-y2,'x',(a+b)/2) > 0
disp(['tich phan can tinh I= ' num2str(I)])
else
disp(['tich phan can tinh I= ' num2str(-I)])
end
end

function n4b6
syms x y real
f=input('f(x,y)= ');
g=input('g(x,y)= ');
disp('nhap toa do 3 dinh A,B,C. vidu: toa do la A(1,2) ta nhap: 1,2')
A=input('toa do A: ','s');A=str2num(A); %chuyen tu kieu string sang kieu so
B=input('toa do B: ','s');B=str2num(B);
C=input('toa do C: ','s');C=str2num(C);
u=diff(g,'y')-diff(f,'x');
dinh=[A;B;C];
a=unique(dinh,'rows'); %sap xep cac dinh cua tam giac, theo chieu tang dan x
S=0;
if size(a,1)~=3
disp('nhap 3 dinh bi sai')
return
end
if a(1,1)~=a(2,1) && a(2,1)~=a(3,1) %neu 3 dinh khong trung x. co 2 mien lay tich phan
vt1=a(1,:)-a(2,:);
vt2=a(1,:)-a(3,:);
y1=(vt1(1,2)*(x-a(1,1))+vt1(1,1)*a(1,2))/vt1(1,1); %phuong trinh duong thang
y2=(vt2(1,2)*(x-a(1,1))+vt2(1,1)*a(1,2))/vt2(1,1);
if subs(y1-y2,'x',(a(2,1)-a(1,1))/2)>0 % xem y1 hay y2 nam tren
S=S+int(int(u,'y',y2,y1),'x',a(1,1),a(2,1)); %tich phan kep
else
S=S+int(int(u,'y',y1,y2),'x',a(1,1),a(2,1));%tich phan kep
end
vt1=a(2,:)-a(3,:);
vt2=a(1,:)-a(3,:);
y1=(vt1(1,2)*(x-a(3,1))+vt1(1,1)*a(3,2))/vt1(1,1);
y2=(vt2(1,2)*(x-a(3,1))+vt2(1,1)*a(3,2))/vt2(1,1);
if subs(y1-y2,'x',(a(3,1)-a(2,1))/2)>0
S=S+int(int(u,'y',y2,y1),'x',a(2,1),a(3,1));%tich phan kep
else
S=S+int(int(u,'y',y1,y2),'x',a(2,1),a(3,1));%tich phan kep
end
elseif a(1,1)==a(2,1) % 2 dinh dau trung nhau, vd: (1,2) , (1,3) , (3,4). ta chi co 1
mien lay tich phan
vt1=a(2,:)-a(3,:);
vt2=a(1,:)-a(3,:);
y1=(vt1(1,2)*(x-a(3,1))+vt1(1,1)*a(3,2))/vt1(1,1);
y2=(vt2(1,2)*(x-a(3,1))+vt2(1,1)*a(3,2))/vt2(1,1);
if subs(y1-y2,'x',(a(3,1)-a(2,1))/2)>0
S=S+int(int(u,'y',y2,y1),'x',a(2,1),a(3,1));%tich phan kep
else
S=S+int(int(u,'y',y1,y2),'x',a(2,1),a(3,1));%tich phan kep
end
elseif a(2,1)==a(3,1) % 2 dinh sau trung nhau, vd: (1,2) , (3,3) , (3,4). ta chi co 1
mien lay tich phan
vt1=a(1,:)-a(2,:);
vt2=a(1,:)-a(3,:);
y1=(vt1(1,2)*(x-a(1,1))+vt1(1,1)*a(1,2))/vt1(1,1);
y2=(vt2(1,2)*(x-a(1,1))+vt2(1,1)*a(1,2))/vt2(1,1);
if subs(y1-y2,'x',(a(2,1)-a(1,1))/2)>0
S=S+int(int(u,'y',y2,y1),'x',a(1,1),a(2,1));%tich phan kep
else
S=S+int(int(u,'y',y1,y2),'x',a(1,1),a(2,1));%tich phan kep
end
end
S=double(S);
disp(['tich phan can tinh la: I= ' num2str(S)])
end

NHÓM 5:
function cau1
clc
disp('nhap cac so a,b thuoc x^2/a^2+y^2/b^2=1')
a=input('a= ');
b=input('b= ');
[x,z]=meshgrid(-a:.2:a);
y=b*sqrt(1-x.^2/a^2);
subplot(1,2,1) %
set(surf(x,y,z),'facecolor','b','edgecolor','r','facealpha',.5)
hold on
y=-b*sqrt(1-x.^2/a^2);
set(surf(x,y,z),'facecolor','b','edgecolor','r','facealpha',.5)
title(['x^2/' num2str(a) '^2 + y^2/' num2str(b) '^2 = 1'])
xlabel('truc x')
ylabel('truc y')
zlabel('truc z')
hold off
[x,z]=meshgrid(-2:.2:2);
y=x.^2;
subplot(1,2,2)
set(surf(x,y,z),'facecolor','b','edgecolor','r','facealpha',.5)
title('y = x^2')
rotate3d on
xlabel('truc x')
ylabel('truc y')
zlabel('truc z')
end

function cau2
clc
syms u v x y real
f=input('f(u,v)= ');
f=sym(f);
u=input('u(x,y)= ');u=sym(u);
v=input('v(x,y)= ');v=sym(v);
f=eval(f); %the u v vao f
fx=diff(f,'x'); %dao ham theo x
fy=diff(f,'y'); %dao ham theo x
disp('nhap toa do M0(x0,y0)')
x0=input('x0= ');x=x0;
y0=input('y0= ');y=y0;
z0=eval(f); %the x0 y0 vao f ta dc z0
fx1=eval(fx); %the x0 y0 vao f'x
fy1=eval(fy); %the x0 y0 vao f'y
disp(['f`x(' num2str(x) ',' num2str(y) ')= ' num2str(fx1)])
disp(['f`y(' num2str(x) ',' num2str(y) ')= ' num2str(fy1)])
%ve hinh
[x,y]=meshgrid(x0-2:.1:x0+2,y0-2:.1:y0+2);
f=[char(f) '+0*x'];
f=strrep(f,'^','.^');f=strrep(f,'*','.*');
f=eval(f);
set(surf(x,y,f),'facecolor','b','edgecolor','g','facealpha',.4)
hold on
%ve tiep tuyen minh hoa y nghia hinh hoc f'x
t=linspace(-2,2,40);
x=x0+t;
y=y0+0*t;
z=z0+fx1*t;
plot3(x,y,z,'r','linewidth',2)
%ve tiep tuyen minh hoa y nghia hinh hoc f'y
x=x0+0*t;
y=y0+t;
z=z0+fy1*t;
plot3(x,y,z,'r','linewidth',2)
text(x0,y0,z0+2,['M0(' num2str(x0) ',' num2str(y0) ',' num2str(z0) ')'])
hold off
xlabel('Ox')
ylabel('Oy')
zlabel('Oz')
rotate3d on
end

function cau3
clc
warning off
syms x y real
f=input('nhap ham f(x,y)= ');
[a b]=solve([char(diff(f,'x')) '+0*x=0'],[char(diff(f,'y')) '+0*y=0'],'x','y'); % giai dao
ham cap 1
[a b]=voso(a,b); % loai vo so nghiem
a=double(a);
b=double(b);

c=zeros(0,3);
for i=1:length(a)
x=a(i);y=b(i);
if abs(x)+abs(y) < 1
c=[c;eval(f) a(i) b(i)];
end
end

syms x real
y=1-x;
c=ctridk(f,y,0,1,c); %tim cuc tri co dk

y=x-1;
c=ctridk(f,y,0,1,c);%tim cuc tri co dk

y=1+x;
c=ctridk(f,y,-1,0,c);%tim cuc tri co dk

y=-1-x;
c=ctridk(f,y,-1,0,c);%tim cuc tri co dk

[x,y]=meshgrid(-1:.02:1);
z=[char(f) '+0*x'];z=strrep(z,'^','.^');z=strrep(z,'*','.*');z=eval(z);
[x y z]=khu(x,y,z);
set(surf(x,y,z),'facecolor','b','edgecolor','non','facealpha',.4)
hold on
rotate3d on

x=1;y=0;c=[c;eval(f) x y];
x=0;y=1;c=[c;eval(f) x y];
x=-1;y=0;c=[c;eval(f) x y];
x=0;y=-1;c=[c;eval(f) x y];

c=double(c);
a=max(c(:,1));
b=min(c(:,1));
d=(a-b)/10;
d(a==inf)=10;
d(b==-inf)=10;
if a==b
if a>subs(f,[x y],[x0+0.12 y0+0.12])
disp(['GTLN f(' num2str(c(1,2)) ',' num2str(c(1,3)) ')= ' num2str(c(1,1))])
else
disp(['GTNN f(' num2str(c(1,2)) ',' num2str(c(1,3)) ')= ' num2str(c(1,1))])
end
return
end
GTLN='GTLN la ';
GTNN='GTNN la ';

for i=1:size(c)
if c(i,1)==a
GTLN=[GTLN 'f(' num2str(c(i,2)) ',' num2str(c(i,3)) ')= '];
text(c(i,2),c(i,3),a+d,['GTLN (' num2str(c(i,2)) ',' num2str(c(i,3)) ',' num2str(a)
')' ])
x=[c(i,2)-d/10 c(i,2) c(i,2)+d/10];
y=[c(i,3)-d/10 c(i,3) c(i,3)+d/10];
z=[a-d/10 a a+d/10];
plot3(x,y,z,'r','linewidth',5)
elseif c(i,1)==b
GTNN=[GTNN 'f(' num2str(c(i,2)) ',' num2str(c(i,3)) ')= '];
text(c(i,2),c(i,3),b-d,['GTNN (' num2str(c(i,2)) ',' num2str(c(i,3)) ',' num2str(b)
')' ])
x=[c(i,2)-d/10 c(i,2) c(i,2)+d/10];
y=[c(i,3)-d/10 c(i,3) c(i,3)+d/10];
z=[b-d/10 b b+d/10];
plot3(x,y,z,'r','linewidth',5)
end
end

if a==Inf
GTLN=('ham f(x,y) khong co GTLN (vo cuc)');
else
GTLN=[GTLN num2str(a)];
end
if b==-Inf
GTNN=('ham f(x,y) khong co GTNN (vo cuc)');
else
GTNN=[GTNN num2str(b)];
end

axis([-1.2 1.2 -1.2 1.2])


disp(GTLN)
disp(GTNN)
xlabel('truc x')
ylabel('truc y')
zlabel('truc z')
hold off
end

%loai cac diem nam ngoai hinh vuong


function [x y z]=khu(x,y,z)
for i=1:length(x)
for j=1:length(y)
if abs(x(i,j))+abs(y(i,j)) > 1 || imag(z(i,j))~=0
z(i,j)=NaN;x(i,j)=NaN;y(i,j)=NaN;
end
end
end
end
%loai nghiem so phuc
function a=loai(a)
n=length(a);
i=1;
while i<=n
if abs(imag(a(i))) > 0.000000000000000000000000000001
a(i)=[];
n=n-1;
else
a(i)=a(i)-imag(a(i))*1i;
i=i+1;
end
end
a=unique(a);
end
%loai vo so nghiem
function [a b]=voso(a,b)
i=1;
n=length(a);
while i<=n
if ~isempty(strfind(char(a(i)),'u')) || ~isempty(strfind(char(b(i)),'u'))
a(i,:)=[];
b(i,:)=[];
n=n-1;
else
i=i+1;
end
end
end
%ham tim cac diem cuc tri co dk
function c=ctridk(f,y,a,b,c)
syms x real
y=y;
z=eval(f);z=sym(z);
d=solve(diff(z));d=double(d);
d=loai(d);
d(d<=a)=[];d(d>=b)=[];
for i=1:length(d)
x=d(i);
c=[c;eval(z) d(i) eval(y)];
end
end

function cau4
clc
warning off
syms y x
f=input('f(x,y)= ');
x1=input('x1(y)= ');
x2=input('x2(y)= ');
x1=sym(x1);
x2=sym(x2);
disp('nhap y thuoc [a,b] ')
a=input('a= ');
b=input('b= ');
c=solve(x1-x2);
c=double(c);
c=c(c>a);
c=c(c<b);
if ~isempty(c)
disp('x1 va x2 cat nhau trong [a,b] tai cac diem co y = ')
disp(c)
return
end
if double(subs((x1-x2),'y',(a+b)/2)) > 0 % neu x1 nam ben phai x2
I=int(int(f,'x',x2,x1),'y',a,b);
I=double(I);
disp(['tich phan can tinh I= ' num2str(I)])
ve(x1,x2,a,b)
else % neu x2 nam ben phai x1
I=int(int(f,'x',x1,x2),'y',a,b);
I=double(I);
disp(['tich phan can tinh I= ' num2str(I)])
ve(x2,x1,a,b)
end
end
%ve mien
function ve(x1,x2,a,b)
syms x y
x1=sym(x1);x1=[char(x1) '+0*y'];
x2=sym(x2);x2=[char(x2) '+0*y'];
y=linspace(a,b,25);
x1=strrep(x1,'^','.^');x1=strrep(x1,'*','.*');
xa=eval(x1);
ya=y;
y=linspace(b,a,25);
x2=strrep(x2,'^','.^');x2=strrep(x2,'*','.*');
x=eval(x2);
xa=[xa x];
ya=[ya y];
fill(xa,ya,'g')
axis([min(xa)-(max(xa)-min(xa))/7 max(xa)+(max(xa)-min(xa))/7 a-(b-a)/7 b+(b-a)/7])
grid on
end

function cau5
clc
syms x y z p phi t real
f=input('f(x,y,z)= ');
f=sym(f);

[x,y,z]=ellipsoid(0,0,1/2,1/2,1/2,1/2);
for i=1:length(x)
for j=1:length(x)
if z(i,j)<0.5
z(i,j)=NaN;
end
end
end
surf(x,y,z)
hold on
z=sqrt(x.^2+y.^2);
surf(x,y,z)
hold off
rotate3d on

x=p*sin(t)*cos(phi);
y=p*sin(t)*sin(phi);
z=p*cos(t);

f=eval(f);
I=int(int(int(f*(p^2)*sin(t),'p',0,cos(t)),'phi',0,2*pi),'t',0,pi/4);
I=double(I);
disp(['I= ' num2str(I)])
disp('ta dat: ')
disp('x=p*sin(t)*cos(phi)')
disp('y=p*sin(t)*sin(phi)')
disp('z=p*cos(t)')
disp('can tich phan la:')
disp('p tu 0 -> cos(t)')
disp('phi tu 0 -> 2pi')
disp('t tu 0 -> pi/4')
end

function cau6
clc
syms x y real
f=input('f(x,y)= ');
g=input('g(x,y)= ');
disp('nhap toa do 3 dinh A,B,C. vidu: toa do la A(1,2) ta nhap: 1,2')
A=input('toa do A: ','s');A=str2num(A); %chuyen tu kieu string sang kieu so
B=input('toa do B: ','s');B=str2num(B);
C=input('toa do C: ','s');C=str2num(C);
u=diff(g,'x')-diff(f,'y');
u=-u; % theo chieu kim dong ho
dinh=[A;B;C];
a=unique(dinh,'rows'); %sap xep cac dinh cua tam giac, theo chieu tang dan x
S=0;
if size(a,1)~=3
disp('nhap 3 dinh bi sai')
return
end

if a(1,1)~=a(2,1) && a(2,1)~=a(3,1) %neu 3 dinh khong trung x. co 2 mien lay tich phan
vt1=a(1,:)-a(2,:);
vt2=a(1,:)-a(3,:);
y1=(vt1(1,2)*(x-a(1,1))+vt1(1,1)*a(1,2))/vt1(1,1); %phuong trinh duong thang
y2=(vt2(1,2)*(x-a(1,1))+vt2(1,1)*a(1,2))/vt2(1,1);
if subs(y1-y2,'x',(a(2,1)-a(1,1))/2)>0 % xem y1 hay y2 nam tren
S=S+int(int(u,'y',y2,y1),'x',a(1,1),a(2,1)); %tich phan kep
else
S=S+int(int(u,'y',y1,y2),'x',a(1,1),a(2,1));%tich phan kep
end
vt1=a(2,:)-a(3,:);
vt2=a(1,:)-a(3,:);
y1=(vt1(1,2)*(x-a(3,1))+vt1(1,1)*a(3,2))/vt1(1,1);
y2=(vt2(1,2)*(x-a(3,1))+vt2(1,1)*a(3,2))/vt2(1,1);
if subs(y1-y2,'x',(a(3,1)-a(2,1))/2)>0
S=S+int(int(u,'y',y2,y1),'x',a(2,1),a(3,1));%tich phan kep
else
S=S+int(int(u,'y',y1,y2),'x',a(2,1),a(3,1));%tich phan kep
end
elseif a(1,1)==a(2,1) % 2 dinh dau trung nhau, vd: (1,2) , (1,3) , (3,4). ta chi co 1
mien lay tich phan
vt1=a(2,:)-a(3,:);
vt2=a(1,:)-a(3,:);
y1=(vt1(1,2)*(x-a(3,1))+vt1(1,1)*a(3,2))/vt1(1,1);
y2=(vt2(1,2)*(x-a(3,1))+vt2(1,1)*a(3,2))/vt2(1,1);
if subs(y1-y2,'x',(a(3,1)-a(2,1))/2)>0
S=S+int(int(u,'y',y2,y1),'x',a(2,1),a(3,1));%tich phan kep
else
S=S+int(int(u,'y',y1,y2),'x',a(2,1),a(3,1));%tich phan kep
end
elseif a(2,1)==a(3,1) % 2 dinh sau trung nhau, vd: (1,2) , (3,3) , (3,4). ta chi co 1
mien lay tich phan
vt1=a(1,:)-a(2,:);
vt2=a(1,:)-a(3,:);
y1=(vt1(1,2)*(x-a(1,1))+vt1(1,1)*a(1,2))/vt1(1,1);
y2=(vt2(1,2)*(x-a(1,1))+vt2(1,1)*a(1,2))/vt2(1,1);
if subs(y1-y2,'x',(a(2,1)-a(1,1))/2)>0
S=S+int(int(u,'y',y2,y1),'x',a(1,1),a(2,1));%tich phan kep
else
S=S+int(int(u,'y',y1,y2),'x',a(1,1),a(2,1));%tich phan kep
end
end
S=double(S);
disp(['tich phan can tinh la: I= ' num2str(S)])
x=a(:,1);
y=a(:,2);
fill(x,y,'b')
text(a(1,1),a(1,2),['(' num2str(a(1,1)) ',' num2str(a(1,2)) ')'])
text(a(2,1),a(2,2),['(' num2str(a(2,1)) ',' num2str(a(2,2)) ')'])
text(a(3,1),a(3,2),['(' num2str(a(3,1)) ',' num2str(a(3,2)) ')'])
grid on
axis([a(1,1)-(a(3,1)-a(1,1))/8 a(3,1)+(a(3,1)-a(1,1))/8 min(a(:,2))-(max(a(:,2))-
min(a(:,2)))/8 max(a(:,2))+(max(a(:,2))-min(a(:,2)))/8])
end

function cau7
clc
disp('nhap toa do M0(x0,y0,y0) thuoc mat cau x^2+y^2+z^2=4')
x0=input('x0= ');
y0=input('y0= ');
z0=input('z0= ');
if abs(x0^2+y0^2+z0^2-4)>0.00001 %kiem tra M0
disp('nhap sai M0')
return
end
syms x y z t p phi real
f=x^2+y^2+z^2-4;
u=3*(x^2+y^2+z^2);
n=[diff(f,'x') diff(f,'y') diff(f,'z')];
n=n/sqrt(diff(f,'x')^2+diff(f,'y')^2+diff(f,'z')^2);
x=p*sin(t)*cos(phi);
y=p*sin(t)*sin(phi);
z=p*cos(t);
u=eval(u);
I=int(int(int(u*p^2*sin(t),'p',0,2),'phi',0,2*pi),'t',0,pi);
I=double(I);
disp(['I= ' num2str(I)])

[x,y,z]=ellipsoid(0,0,0,2,2,2);
set(surf(x,y,z),'facecolor','b','edgecolor','g','facealpha',.3)
hold on
rotate3d on
x=x0;y=y0;z=z0;
n=eval(n);
x=n(1);
y=n(2);
z=n(3);
disp(['vector phap tai M0(' num2str(x0) ',' num2str(y0) ',' num2str(z0) ') la:'])
disp(['n= (' num2str(n(1)) ',' num2str(n(2)) ',' num2str(n(3)) ')'])
quiver3(x0,y0,z0,x,y,z,.5,'r','LineWidth',2)
hold off
axis([-2.5 2.5 -2.5 2.5 -2.5 2.5])
xlabel('Ox')
ylabel('Oy')
zlabel('Oz')
end

function ve
clc
%code ve mat bac 2
disp('nhap lan luoc a b c d e f g cua mat bac 2theo cong thuc sau:')
disp('a*x^2 + b*y^2/b^2 + c*z^2 + d*xy + e*xz + f*yz + g*x + h*y + i*z = j')
a=input('a= ');
b=input('b= ');
c=input('c= ');
d=input('d= ');
e=input('e= ');
f=input('f= ');
g=input('g= ');
h=input('h= ');
i=input('i= ');
j=input('j= ');
disp('nhap cac gioi han cua x y z')
x0=input('|x|< ');
y0=input('|y|< ');
z0=input('|z|< ');
phi=linspace(0,2*pi,40);
theta=linspace(0,pi,40);
[phi theta]=meshgrid(phi,theta);
x=zeros(40);
y=x;z=x;
for k=1:40
for q=1:40
xx=(sin(theta(k,q))*cos(phi(k,q)))^2;
yy=(sin(theta(k,q))*sin(phi(k,q)))^2;
zz=(cos(theta(k,q)))^2;
xy=sin(theta(k,q))^2*cos(phi(k,q))*sin(phi(k,q));
xz=sin(theta(k,q))*cos(phi(k,q))*cos(theta(k,q));
yz=sin(theta(k,q))*sin(phi(k,q))*cos(theta(k,q));
x1=sin(theta(k,q))*cos(phi(k,q));
y1=sin(theta(k,q))*sin(phi(k,q));
z1=cos(theta(k,q));
A1=a*xx + b*yy + c*zz;
A2=2*(d*xy + e*xz + f*yz);
A=A1+A2;
B= g*x1 + h*y1 + i*z1;
C=-j;
delta=B^2-4*A*C;
if delta < 0
R=NaN;
else
R=(-B+sqrt(delta))/(2*A);
end
x(k,q)=R*sin(theta(k,q))*cos(phi(k,q));
y(k,q)=R*sin(theta(k,q))*sin(phi(k,q));
z(k,q)=R*cos(theta(k,q));
if abs(x(k,q)) > x0 || abs(y(k,q)) > y0 || abs(z(k,q)) > z0
x(k,q)=NaN;
y(k,q)=NaN;
z(k,q)=NaN;
end
end
end
surf(x,y,z)
end

VẼ MẶT CONG:
VD1: TÍCH PHÂN BỘI:
clf
s=linspace(-1,1,30);
s1=meshgrid(s);t1=[];
for i=1:length(s)
tam=linspace(s(i)^2,1,30);
t1=[t1 tam'];
end
x=s1;y=t1;z=1-y;z1=0*x;
hold on
surf(x,y,z,'FaceColor','g','EdgeColor','g','FaceAlpha',0.3);
surf(x,y,z1,'FaceColor','r','EdgeColor','none');
s=linspace(-1,1,30);
t1=[];
for i=1:length(s)
tam=linspace(0,1-s(i)^2,30);
t1=[t1 tam'];
end
x=s1;z=t1;y=s1.^2;
surf(x,y,z,'FaceColor','b','EdgeColor','none','FaceAlpha',0.5);
view(120,12)
grid on
rotate3d on

VD1: TÍCH PHÂN KÉP:


clc
clf
% y=sqrt(x); y=0; z=0; x+z=1
hold on
s=linspace(0,1,30);
s1=meshgrid(s);
%%%%%%%%%%%%% Phan mat z=0 va x+z=1 %%%%%%%%%%%%%%%%
t=[];
for i=1:length(s)
tam=linspace(0,sqrt(s(i)),30);
t=[t tam'];
end
x=s1;y=t;z=0*x;z1=1-s1;
surf(x,y,z,'FaceColor','b','EdgeColor','none');
mesh(x,y,z1,'EdgeColor','r','FaceAlpha',0.1);
%%%%%%%%%%%% Phan mat y=0 %%%%%%%%%%%%%%%%%%%
t=[];
for i=1:length(s)
tam=linspace(0,1-s(i),30);
t=[t tam'];
end
x=s1;z=t;y=0*x;
surf(x,y,z,'FaceColor','r','EdgeColor','none','FaceAlpha',0.5);
%%%%%%%%%%%% Phan mat x= y^2 %%%%%%%%%%%%%%%%%
t=[];
for i=1:length(s)
tam=linspace(0,1-(s(i))^2,30);
t=[t tam'];
end
y=s1;z=t;x=y.^2;x1=0*s1;
surf(x,y,z,'FaceColor','y','EdgeColor','none','FaceAlpha',0.5);
surf(x1,y,z,'FaceColor','m','EdgeColor','none','FaceAlpha',0.1);
view(115,20)
grid on
rotate3d on

VD2: TÍCH PHÂN BỘI:


clf
s=linspace(0,3,30);
s1=meshgrid(s);
t1=[];
%%%%%%%%%%%% Toan mat chan x+y+z=3 %%%%%%%%%%%%%
for i=1:length(s)
tam=linspace(0,3-s(i),30);
t1=[t1 tam'];
end
hold on
y=s1;x=t1;z=3-x-y;
surf(x,y,z,'EdgeColor','none','FaceColor','r','FaceAlpha',0.2);
%%%%%%%%%%%% Phan mat x+y+z=3 va z=0 %%%%%%%%%%
t1=[];
for i=1:length(s)
tam=linspace(1-s(i)/3,2-2*s(i)/3,30);
t1=[t1 tam'];
end;
y=s1;x=t1;z=3-x-y;z1=0*x;
mesh(x,y,z,'EdgeColor','r','FaceAlpha',0.3);
surf(x,y,z1,'EdgeColor','none','FaceColor','g');
%%%%%%%%%% Phan mat 3x+2y=6%%%%%%%%%%%%%
t1=[];
for i=1:length(s)
tam=linspace(0,1-s(i)/3,30);
t1=[t1 tam'];
end
z=t1;x=1/3*(6-2*y);
mesh(x,y,z,'EdgeColor','b','FaceAlpha',0.3);
%%%%%%%%%% Phan mat 3x+y=3%%%%%%%%%%%%%
t1=[];
for i=1:length(s)
tam=linspace(0,2*(1-s(i)/3),30);
t1=[t1 tam'];
end;
z=t1;x=1/3*(3-y);
surf(x,y,z,'EdgeColor','none','FaceColor','y');
%%%%%%%%%% Phan mat y=0 %%%%%%%%%%%%%
s=linspace(1,2,30);
s1=meshgrid(s);t1=[];
for i=1:length(s)
tam=linspace(0,3-s(i),30);
t1=[t1 tam'];
end;
x=s1;z=t1;y=0*x;
surf(x,y,z,'EdgeColor','none','FaceColor','m');
view(130,18);
grid on;
rotate3d on

VD2: TÍCH PHÂN KÉP:


clf
hold on
cylinderd(sqrt(2),sqrt(2),0,2);
phi=linspace(0,2*pi,30);
r=linspace(0,sqrt(2),30);
[r phi]=meshgrid(r,phi);
x=r.*cos(phi);
y=r.*sin(phi);
z=4-x.^2-y.^2;z1=0*x;
surf(x,y,z,'FaceColor','g','EdgeColor','g','FaceAlpha',0.3);
surf(x,y,z1,'FaceColor','b','EdgeColor','b','FaceAlpha',0.3);
grid on
view (13,28)

VD3: TÍCH PHÂN BỘI:


clf
hold on
%%%%%%%%%%%%%%%%% Non %%%%%%%%%%%%%%%%%%
phi=linspace(0,2*pi,30);
r=linspace(0,1,30);
[r phi]=meshgrid(r,phi);
x=r.*cos(phi);
y=r.*sin(phi);
z=sqrt(x.^2+y.^2);
surfc(x,y,z,'FaceColor','b','EdgeColor','r','FaceAlpha',0.7);
%%%%%%%%%%%%%%%%% Nua cau tren %%%%%%%%%%%%%%%%%%
phi=linspace(0,2*pi,30);
theta=linspace(0,pi/2,30);
[p t]=meshgrid(phi,theta);
x=sqrt(2)*sin(t).*cos(p);
y=sqrt(2)*sin(t).*sin(p);
z=sqrt(2)*cos(t);
mesh(x,y,z,'FaceColor','r','FaceAlpha',0.2,'EdgeColor','none');
%%%%%%%%%%%%%%%%% Chom cau %%%%%%%%%%%%%%%%%%%%
phi=linspace(0,2*pi,30);
theta=linspace(0,pi/4,30);
[p t]=meshgrid(phi,theta);
x=sqrt(2)*sin(t).*cos(p);
y=sqrt(2)*sin(t).*sin(p);
z=sqrt(2)*cos(t);
mesh(x,y,z,'FaceColor','m','FaceAlpha',0.3,'EdgeColor','m');
%%%%%%%%%%%%%%%%% Giao tuyen %%%%%%%%%%%%%
x=cos(phi);y=sin(phi);z=1+0*x;
plot3(x,y,z,'-y','linewidth',3)
grid on
view(6,34)
rotate3d on

VD3: TÍCH PHÂN KÉP:


clf
hold on
phi=linspace(0,2*pi,30);
r=linspace(0,sqrt(2),30);
[r phi]=meshgrid(r,phi);
x=r.*cos(phi);
y=r.*sin(phi);
z=4-x.^2-y.^2;z1=1+(x.^2+y.^2)/2;z2=0*x;
surf(x,y,z,'FaceColor','g','EdgeColor','w','FaceAlpha',0.3);
surfc(x,y,z1,'FaceColor','r','EdgeColor','r','FaceAlpha',0.3);
surf(x,y,z2,'FaceColor','b','EdgeColor','non','FaceAlpha',1);
grid on
axis square
view (17,14)
rotate3d on

VD4: TÍCH PHÂN BỘI:


clf
hold on
%%%%%%%%%%%%%%%%% Non %%%%%%%%%%%%%%%%%%
phi=linspace(0,2*pi,30);
r=linspace(0,1,30);
[r phi]=meshgrid(r,phi);
x=r.*cos(phi);
y=r.*sin(phi);
z=sqrt(x.^2+y.^2);
surfc(x,y,z,'FaceColor','b','EdgeColor','non','FaceAlpha',0.7);
%%%%%%%%%%%%%%%%% Cau %%%%%%%%%%%%%%%%%%
phi=linspace(0,2*pi,30);
theta=linspace(pi/2,pi,30);
[p t]=meshgrid(phi,theta);
x=sin(t).*cos(p);
y=sin(t).*sin(p);
z=cos(t)+1;
mesh(x,y,z,'FaceColor','r','FaceAlpha',0.3,'EdgeColor','w');
%%%%%%%%%%%%%%%%% Giao tuyen %%%%%%%%%%%%%
x=cos(phi);y=sin(phi);z=1+0*x;
plot3(x,y,z,'-y','linewidth',3)
grid on
view(6,34)
rotate3d on

VD4: TÍCH PHÂN KÉP:


clf
hold on
%%%%%%%%%%%%%% Toan mat paraboloid %%%%%%%%%%
phi=linspace(0,2*pi,30);
r=linspace(0,1,30);
[r phi]=meshgrid(r,phi);
x=r.*cos(phi);y=sqrt(2)*r.*sin(phi);
z=2*x.^2+y.^2+1;
surf(x,y,z,'FaceColor','r','EdgeColor','non','FaceAlpha',0.2);
%%%%%%%%%%%%%%% Mat paraboloid va mat z=0%%%%%%%%%%%%
s=linspace(0,1,30);
s1=[];t1=[];
for i=1:length(s)
s1(i,:)=s;
tam=linspace(0,1-s(i),30);
t1=[t1 tam'];
end
x=s1;y=t1;z=2*x.^2+y.^2+1;z1=0*x;
surf(x,y,z,'FaceColor','r','EdgeColor','non','FaceAlpha',0.8);
surf(x,y,z1,'FaceColor','g','EdgeColor','non','FaceAlpha',1);
%%%%%%%%%%%%%%% Mat x+y=1 %%%%%%%%%%%%%%%%%%%%
t1=[];
for i=1:length(s)
tam=linspace(0,3+3*s(i)^2-4*s(i),30);
t1=[t1 tam'];
end;
y=s1;z=t1;x=1-y;
mesh(x,y,z,'FaceColor','y','EdgeColor','y','FaceAlpha',0.1);
%%%%%%%%%%%%%%%% Mat y = 0 %%%%%%%%%%%%%%%%%
t1=[];
for i=1:length(s)
tam=linspace(0,1+2*s(i)^2,30);
t1=[t1 tam'];
end;
x=s1;z=t1;y=0*x;
surf(x,y,z,'FaceColor','b','EdgeColor','non','FaceAlpha',0.5);
%%%%%%%%%%%%%%%%%%% Mat x = 0 %%%%%%%%%%%%%%%
t1=[];
for i=1:length(s)
tam=linspace(0,1+s(i)^2,30);
t1=[t1 tam'];
end;
y=s1;z=t1;x=0*y;
surf(x,y,z,'FaceColor','m','EdgeColor','non','FaceAlpha',0.7);
grid on
view(136,18)
xlabel('x')
ylabel('y')
zlabel('z')
axis square
rotate3d on

VD5: TÍCH PHÂN KÉP:


clf
hold on
phi=linspace(0,2*pi,30);
r=linspace(0,1,40);
[r ph]=meshgrid(r,phi);
%%%%%%%%%%%%%% Phan mat cau va mat z = 0%%%%%%%%%%%%%
x=r.*cos(ph);
y=r.*sin(ph)+1;
z=sqrt(4-x.^2-y.^2);z1=0*x;
surf(x,y,z,'FaceColor','r','FaceAlpha',0.3,'EdgeColor','y');
surf(x,y,z1,'FaceColor','g','FaceAlpha',1,'EdgeColor','w');
%%%%%%%%%%%%%% Phan mat tru %%%%%%%%%%%%%%%%%%%%%%%
x=cos(ph);y=sin(ph)+1;z=r.*sqrt(2-2*sin(ph));
mesh(x,y,z,'FaceColor','b','FaceAlpha',0.3,'EdgeColor','non');
xlabel('x')
ylabel('y')
zlabel('z')
view(105,20)
grid on
axis square
rotate3d on
VD1: VẼ KHỐI:

clf
hold on

s=linspace(-1,1,100);
s1=[];t1=[];
for i=1:length(s)
s1(i,:)=s;
tam=linspace(s(i).^2,sqrt(2-s(i).^2),100);
t1=[t1 tam'];
end
x=s1;y=t1;z=x.^2+y.^2;z1=2+0*x;;
surf(x,y,z,'FaceColor','r','EdgeColor','non','FaceAlpha',0.8);
surf(x,y,z1,'FaceColor','g','EdgeColor','none');

s=linspace(-1,1,30);s1=meshgrid(s);
t1=[];
for i=1:length(s)
tam=linspace(s(i)^2+s(i)^4,2,30);
t1=[t1 tam'];
end
x=s1;z=t1;y=s1.^2;
surf(x,y,z,'FaceColor','b','EdgeColor','none','FaceAlpha',0.5);
grid on
view(136,18)

rotate3d on

%%%%%Ve mien gioi han boi cac mat z=x^2+y^2,z=2,y=x^2

VD2: VẼ KHỐI:
clf
hold on
phi=linspace(0,2*pi,100);r=linspace(-1,1,100);

[r,phi]=meshgrid(r,phi);
y=cos(phi);z=sin(phi);x=r.*sqrt((sin(phi)+2).^2-(cos(phi)).^2);
mesh(x,y,z,'FaceColor','b','FaceAlpha',0.3,'EdgeColor','non');

r1=linspace(0,1,100);[r1]=meshgrid(r1);

y=r1.*cos(phi);
z=r1.*sin(phi);
x1=-sqrt((z+2).^2-y.^2);x2=sqrt((z+2).^2-y.^2);
surf(x1,y,z,'FaceColor','r','FaceAlpha',0.3,'EdgeColor','y');
surf(x2,y,z,'FaceColor','g','FaceAlpha',1,'EdgeColor','w');

xlabel('x')
ylabel('y')
zlabel('z')
view(105,20)
grid on
axis square
rotate3d on

%%%%%Ve mien gioi han boi mat tru y^2+z^2=1 va mat non z=-2+sqrt(x^2+y^2)

VẼ HÌNH
ARROW
function [h,yy,zz] = arrow(varargin)
% ARROW Draw a line with an arrowhead.
%
% ARROW(Start,Stop) draws a line with an arrow from Start to Stop (points
% should be vectors of length 2 or 3, or matrices with 2 or 3
% columns), and returns the graphics handle of the arrow(s).
%
% ARROW uses the mouse (click-drag) to create an arrow.
%
% ARROW DEMO & ARROW DEMO2 show 3-D & 2-D demos of the capabilities of ARROW.
%
% ARROW may be called with a normal argument list or a property-based list.
% ARROW(Start,Stop,Length,BaseAngle,TipAngle,Width,Page,CrossDir) is
% the full normal argument list, where all but the Start and Stop
% points are optional. If you need to specify a later argument (e.g.,
% Page) but want default values of earlier ones (e.g., TipAngle),
% pass an empty matrix for the earlier ones (e.g., TipAngle=[]).
%
% ARROW('Property1',PropVal1,'Property2',PropVal2,...) creates arrows with the
% given properties, using default values for any unspecified or given as
% 'default' or NaN. Some properties used for line and patch objects are
% used in a modified fashion, others are passed directly to LINE, PATCH,
% or SET. For a detailed properties explanation, call ARROW PROPERTIES.
%
% Start The starting points. B
% Stop The end points. /|\ ^
% Length Length of the arrowhead in pixels. /|||\ |
% BaseAngle Base angle in degrees (ADE). //|||\\ L|
% TipAngle Tip angle in degrees (ABC). ///|||\\\ e|
% Width Width of the base in pixels. ////|||\\\\ n|
% Page Use hardcopy proportions. /////|D|\\\\\ g|
% CrossDir Vector || to arrowhead plane. //// ||| \\\\ t|
% NormalDir Vector out of arrowhead plane. /// ||| \\\ h|
% Ends Which end has an arrowhead. //<----->|| \\ |
% ObjectHandles Vector of handles to update. / base ||| \ V
% E angle||<-------->C
% ARROW(H,'Prop1',PropVal1,...), where H is a |||tipangle
% vector of handles to previously-created arrows |||
% and/or line objects, will update the previously- |||
% created arrows according to the current view -->|A|<-- width
% and any specified properties, and will convert
% two-point line objects to corresponding arrows. ARROW(H) will update
% the arrows if the current view has changed. Root, figure, or axes
% handles included in H are replaced by all descendant Arrow objects.
%
% A property list can follow any specified normal argument list, e.g.,
% ARROW([1 2 3],[0 0 0],36,'BaseAngle',60) creates an arrow from (1,2,3) to
% the origin, with an arrowhead of length 36 pixels and 60-degree base angle.
%
% The basic arguments or properties can generally be vectorized to create
% multiple arrows with the same call. This is done by passing a property
% with one row per arrow, or, if all arrows are to have the same property
% value, just one row may be specified.
%
% You may want to execute AXIS(AXIS) before calling ARROW so it doesn't change
% the axes on you; ARROW determines the sizes of arrow components BEFORE the
% arrow is plotted, so if ARROW changes axis limits, arrows may be malformed.
%
% This version of ARROW uses features of MATLAB 6.x and is incompatible with
% earlier MATLAB versions (ARROW for MATLAB 4.2c is available separately);
% some problems with perspective plots still exist.

% Copyright (c)1995-2009, Dr. Erik A. Johnson <[email protected]>, 5/20/2009


% http://www.usc.edu/civil_eng/johnsone/

% Revision history:
% 5/20/09 EAJ Fix view direction in (3D) demo.
% 6/26/08 EAJ Replace eval('trycmd','catchcmd') with try, trycmd; catch,
% catchcmd; end; -- break's MATLAB 5 compatibility.
% 8/26/03 EAJ Eliminate OpenGL attempted fix since it didn't fix anyway.
% 11/15/02 EAJ Accomodate how MATLAB 6.5 handles NaN and logicals
% 7/28/02 EAJ Tried (but failed) work-around for MATLAB 6.x / OpenGL bug
% if zero 'Width' or not double-ended
% 11/10/99 EAJ Add logical() to eliminate zero index problem in MATLAB 5.3.
% 11/10/99 EAJ Corrected warning if axis limits changed on multiple axes.
% 11/10/99 EAJ Update e-mail address.
% 2/10/99 EAJ Some documentation updating.
% 2/24/98 EAJ Fixed bug if Start~=Stop but both colinear with viewpoint.
% 8/14/97 EAJ Added workaround for MATLAB 5.1 scalar logical transpose bug.
% 7/21/97 EAJ Fixed a few misc bugs.
% 7/14/97 EAJ Make arrow([],'Prop',...) do nothing (no old handles)
% 6/23/97 EAJ MATLAB 5 compatible version, release.
% 5/27/97 EAJ Added Line Arrows back in. Corrected a few bugs.
% 5/26/97 EAJ Changed missing Start/Stop to mouse-selected arrows.
% 5/19/97 EAJ MATLAB 5 compatible version, beta.
% 4/13/97 EAJ MATLAB 5 compatible version, alpha.
% 1/31/97 EAJ Fixed bug with multiple arrows and unspecified Z coords.
% 12/05/96 EAJ Fixed one more bug with log plots and NormalDir specified
% 10/24/96 EAJ Fixed bug with log plots and NormalDir specified
% 11/13/95 EAJ Corrected handling for 'reverse' axis directions
% 10/06/95 EAJ Corrected occasional conflict with SUBPLOT
% 4/24/95 EAJ A major rewrite.
% Fall 94 EAJ Original code.

% Things to be done:
% - in the arrow_clicks section, prompt by printing to the screen so that
% the user knows what's going on; also make sure the figure is brought
% to the front.
% - segment parsing, computing, and plotting into separate subfunctions
% - change computing from Xform to Camera paradigms
% + this will help especially with 3-D perspective plots
% + if the WarpToFill section works right, remove warning code
% + when perpsective works properly, remove perspective warning code
% - add cell property values and struct property name/values (like get/set)
% - get rid of NaN as the "default" data label
% + perhaps change userdata to a struct and don't include (or leave
% empty) the values specified as default; or use a cell containing
% an empty matrix for a default value
% - add functionality of GET to retrieve current values of ARROW properties

% Many thanks to Keith Rogers <[email protected]> for his many excellent


% suggestions and beta testing. Check out his shareware package MATDRAW
% (at ftp://ftp.mathworks.com/pub/contrib/v5/graphics/matdraw/) -- he has
% permission to distribute ARROW with MATDRAW.

% Permission is granted to distribute ARROW with the toolboxes for the book
% "Solving Solid Mechanics Problems with MATLAB 5", by F. Golnaraghi et al.
% (Prentice Hall, 1999).
% Permission is granted to Dr. Josef Bigun to distribute ARROW with his
% software to reproduce the figures in his image analysis text.

% global variable initialization


global ARROW_PERSP_WARN ARROW_STRETCH_WARN ARROW_AXLIMITS
if isempty(ARROW_PERSP_WARN ), ARROW_PERSP_WARN =1; end;
if isempty(ARROW_STRETCH_WARN), ARROW_STRETCH_WARN=1; end;

% Handle callbacks
if (nargin>0 & isstr(varargin{1}) & strcmp(lower(varargin{1}),'callback')),
arrow_callback(varargin{2:end}); return;
end;

% Are we doing the demo?


c = sprintf('\n');
if (nargin==1 & isstr(varargin{1})),
arg1 = lower(varargin{1});
if strncmp(arg1,'prop',4), arrow_props;
elseif strncmp(arg1,'demo',4)
clf reset
demo_info = arrow_demo;
if ~strncmp(arg1,'demo2',5),
hh=arrow_demo3(demo_info);
else,
hh=arrow_demo2(demo_info);
end;
if (nargout>=1), h=hh; end;
elseif strncmp(arg1,'fixlimits',3),
arrow_fixlimits(ARROW_AXLIMITS);
ARROW_AXLIMITS=[];
elseif strncmp(arg1,'help',4),
disp(help(mfilename));
else,
error([upper(mfilename) ' got an unknown single-argument string ''' deblank(arg1)
'''.']);
end;
return;
end;

% Check # of arguments
if (nargout>3), error([upper(mfilename) ' produces at most 3 output arguments.']); end;

% find first property number


firstprop = nargin+1;
for k=1:length(varargin), if ~isnumeric(varargin{k}), firstprop=k; break; end; end;
lastnumeric = firstprop-1;

% check property list


if (firstprop<=nargin),
for k=firstprop:2:nargin,
curarg = varargin{k};
if ~isstr(curarg) | sum(size(curarg)>1)>1,
error([upper(mfilename) ' requires that a property name be a single string.']);
end;
end;
if (rem(nargin-firstprop,2)~=1),
error([upper(mfilename) ' requires that the property ''' ...
varargin{nargin} ''' be paired with a property value.']);
end;
end;

% default output
if (nargout>0), h=[]; end;
if (nargout>1), yy=[]; end;
if (nargout>2), zz=[]; end;

% set values to empty matrices


start = [];
stop = [];
len = [];
baseangle = [];
tipangle = [];
wid = [];
page = [];
crossdir = [];
ends = [];
ax = [];
oldh = [];
ispatch = [];
defstart = [NaN NaN NaN];
defstop = [NaN NaN NaN];
deflen = 16;
defbaseangle = 90;
deftipangle = 16;
defwid = 0;
defpage = 0;
defcrossdir = [NaN NaN NaN];
defends = 1;
defoldh = [];
defispatch = 1;

% The 'Tag' we'll put on our arrows


ArrowTag = 'Arrow';

% check for oldstyle arguments


if (firstprop==2),
% assume arg1 is a set of handles
oldh = varargin{1}(:);
if isempty(oldh), return; end;
elseif (firstprop>9),
error([upper(mfilename) ' takes at most 8 non-property arguments.']);
elseif (firstprop>2),
{start,stop,len,baseangle,tipangle,wid,page,crossdir};
args = [varargin(1:firstprop-1) cell(1,length(ans)-(firstprop-1))];
[start,stop,len,baseangle,tipangle,wid,page,crossdir] = deal(args{:});
end;

% parse property pairs


extraprops={};
for k=firstprop:2:nargin,
prop = varargin{k};
val = varargin{k+1};
prop = [lower(prop(:)') ' '];
if strncmp(prop,'start' ,5), start = val;
elseif strncmp(prop,'stop' ,4), stop = val;
elseif strncmp(prop,'len' ,3), len = val(:);
elseif strncmp(prop,'base' ,4), baseangle = val(:);
elseif strncmp(prop,'tip' ,3), tipangle = val(:);
elseif strncmp(prop,'wid' ,3), wid = val(:);
elseif strncmp(prop,'page' ,4), page = val;
elseif strncmp(prop,'cross' ,5), crossdir = val;
elseif strncmp(prop,'norm' ,4), if (isstr(val)), crossdir=val; else,
crossdir=val*sqrt(-1); end;
elseif strncmp(prop,'end' ,3), ends = val;
elseif strncmp(prop,'object',6), oldh = val(:);
elseif strncmp(prop,'handle',6), oldh = val(:);
elseif strncmp(prop,'type' ,4), ispatch = val;
elseif strncmp(prop,'userd' ,5), %ignore it
else,
% make sure it is a valid patch or line property
try
get(0,['DefaultPatch' varargin{k}]);
catch
errstr = lasterr;
try
get(0,['DefaultLine' varargin{k}]);
catch
errstr(1:max(find(errstr==char(13)|errstr==char(10)))) = '';
error([upper(mfilename) ' got ' errstr]);
end
end;
extraprops={extraprops{:},varargin{k},val};
end;
end;

% Check if we got 'default' values


start = arrow_defcheck(start ,defstart ,'Start' );
stop = arrow_defcheck(stop ,defstop ,'Stop' );
len = arrow_defcheck(len ,deflen ,'Length' );
baseangle = arrow_defcheck(baseangle,defbaseangle,'BaseAngle' );
tipangle = arrow_defcheck(tipangle ,deftipangle ,'TipAngle' );
wid = arrow_defcheck(wid ,defwid ,'Width' );
crossdir = arrow_defcheck(crossdir ,defcrossdir ,'CrossDir' );
page = arrow_defcheck(page ,defpage ,'Page' );
ends = arrow_defcheck(ends ,defends ,'' );
oldh = arrow_defcheck(oldh ,[] ,'ObjectHandles');
ispatch = arrow_defcheck(ispatch ,defispatch ,'' );

% check transpose on arguments


[m,n]=size(start ); if any(m==[2 3])&(n==1|n>3), start = start'; end;
[m,n]=size(stop ); if any(m==[2 3])&(n==1|n>3), stop = stop'; end;
[m,n]=size(crossdir); if any(m==[2 3])&(n==1|n>3), crossdir = crossdir'; end;

% convert strings to numbers


if ~isempty(ends) & isstr(ends),
endsorig = ends;
[m,n] = size(ends);
col = lower([ends(:,1:min(3,n)) ones(m,max(0,3-n))*' ']);
ends = NaN*ones(m,1);
oo = ones(1,m);
ii=find(all(col'==['non']'*oo)'); if ~isempty(ii), ends(ii)=ones(length(ii),1)*0; end;
ii=find(all(col'==['sto']'*oo)'); if ~isempty(ii), ends(ii)=ones(length(ii),1)*1; end;
ii=find(all(col'==['sta']'*oo)'); if ~isempty(ii), ends(ii)=ones(length(ii),1)*2; end;
ii=find(all(col'==['bot']'*oo)'); if ~isempty(ii), ends(ii)=ones(length(ii),1)*3; end;
if any(isnan(ends)),
ii = min(find(isnan(ends)));
error([upper(mfilename) ' does not recognize ''' deblank(endsorig(ii,:)) ''' as a
valid ''Ends'' value.']);
end;
else,
ends = ends(:);
end;
if ~isempty(ispatch) & isstr(ispatch),
col = lower(ispatch(:,1));
patchchar='p'; linechar='l'; defchar=' ';
mask = col~=patchchar & col~=linechar & col~=defchar;
if any(mask),
error([upper(mfilename) ' does not recognize ''' deblank(ispatch(min(find(mask)),:))
''' as a valid ''Type'' value.']);
end;
ispatch = (col==patchchar)*1 + (col==linechar)*0 + (col==defchar)*defispatch;
else,
ispatch = ispatch(:);
end;
oldh = oldh(:);

% check object handles


if ~all(ishandle(oldh)), error([upper(mfilename) ' got invalid object handles.']); end;

% expand root, figure, and axes handles


if ~isempty(oldh),
ohtype = get(oldh,'Type');
mask = strcmp(ohtype,'root') | strcmp(ohtype,'figure') | strcmp(ohtype,'axes');
if any(mask),
oldh = num2cell(oldh);
for ii=find(mask)',
oldh(ii) = {findobj(oldh{ii},'Tag',ArrowTag)};
end;
oldh = cat(1,oldh{:});
if isempty(oldh), return; end; % no arrows to modify, so just leave
end;
end;

% largest argument length


[mstart,junk]=size(start); [mstop,junk]=size(stop); [mcrossdir,junk]=size(crossdir);
argsizes = [length(oldh) mstart mstop ...
length(len) length(baseangle) length(tipangle) ...
length(wid) length(page) mcrossdir length(ends) ];
args=['length(ObjectHandle) '; ...
'#rows(Start) '; ...
'#rows(Stop) '; ...
'length(Length) '; ...
'length(BaseAngle) '; ...
'length(TipAngle) '; ...
'length(Width) '; ...
'length(Page) '; ...
'#rows(CrossDir) '; ...
'#rows(Ends) '];
if (any(imag(crossdir(:))~=0)),
args(9,:) = '#rows(NormalDir) ';
end;
if isempty(oldh),
narrows = max(argsizes);
else,
narrows = length(oldh);
end;
if (narrows<=0), narrows=1; end;

% Check size of arguments


ii = find((argsizes~=0)&(argsizes~=1)&(argsizes~=narrows));
if ~isempty(ii),
s = args(ii',:);
while ((size(s,2)>1)&((abs(s(:,size(s,2)))==0)|(abs(s(:,size(s,2)))==abs(' ')))),
s = s(:,1:size(s,2)-1);
end;
s = [ones(length(ii),1)*[upper(mfilename) ' requires that '] s ...
ones(length(ii),1)*[' equal the # of arrows (' num2str(narrows) ').' c]];
s = s';
s = s(:)';
s = s(1:length(s)-1);
error(setstr(s));
end;
% check element length in Start, Stop, and CrossDir
if ~isempty(start),
[m,n] = size(start);
if (n==2),
start = [start NaN*ones(m,1)];
elseif (n~=3),
error([upper(mfilename) ' requires 2- or 3-element Start points.']);
end;
end;
if ~isempty(stop),
[m,n] = size(stop);
if (n==2),
stop = [stop NaN*ones(m,1)];
elseif (n~=3),
error([upper(mfilename) ' requires 2- or 3-element Stop points.']);
end;
end;
if ~isempty(crossdir),
[m,n] = size(crossdir);
if (n<3),
crossdir = [crossdir NaN*ones(m,3-n)];
elseif (n~=3),
if (all(imag(crossdir(:))==0)),
error([upper(mfilename) ' requires 2- or 3-element CrossDir vectors.']);
else,
error([upper(mfilename) ' requires 2- or 3-element NormalDir vectors.']);
end;
end;
end;

% fill empty arguments


if isempty(start ), start = [Inf Inf Inf]; end;
if isempty(stop ), stop = [Inf Inf Inf]; end;
if isempty(len ), len = Inf; end;
if isempty(baseangle ), baseangle = Inf; end;
if isempty(tipangle ), tipangle = Inf; end;
if isempty(wid ), wid = Inf; end;
if isempty(page ), page = Inf; end;
if isempty(crossdir ), crossdir = [Inf Inf Inf]; end;
if isempty(ends ), ends = Inf; end;
if isempty(ispatch ), ispatch = Inf; end;

% expand single-column arguments


o = ones(narrows,1);
if (size(start ,1)==1), start = o * start ; end;
if (size(stop ,1)==1), stop = o * stop ; end;
if (length(len )==1), len = o * len ; end;
if (length(baseangle )==1), baseangle = o * baseangle ; end;
if (length(tipangle )==1), tipangle = o * tipangle ; end;
if (length(wid )==1), wid = o * wid ; end;
if (length(page )==1), page = o * page ; end;
if (size(crossdir ,1)==1), crossdir = o * crossdir ; end;
if (length(ends )==1), ends = o * ends ; end;
if (length(ispatch )==1), ispatch = o * ispatch ; end;
ax = o * gca;

% if we've got handles, get the defaults from the handles


if ~isempty(oldh),
for k=1:narrows,
oh = oldh(k);
ud = get(oh,'UserData');
ax(k) = get(oh,'Parent');
ohtype = get(oh,'Type');
if strcmp(get(oh,'Tag'),ArrowTag), % if it's an arrow already
if isinf(ispatch(k)), ispatch(k)=strcmp(ohtype,'patch'); end;
% arrow UserData format: [start' stop' len base tip wid page crossdir' ends]
start0 = ud(1:3);
stop0 = ud(4:6);
if (isinf(len(k))), len(k) = ud( 7); end;
if (isinf(baseangle(k))), baseangle(k) = ud( 8); end;
if (isinf(tipangle(k))), tipangle(k) = ud( 9); end;
if (isinf(wid(k))), wid(k) = ud(10); end;
if (isinf(page(k))), page(k) = ud(11); end;
if (isinf(crossdir(k,1))), crossdir(k,1) = ud(12); end;
if (isinf(crossdir(k,2))), crossdir(k,2) = ud(13); end;
if (isinf(crossdir(k,3))), crossdir(k,3) = ud(14); end;
if (isinf(ends(k))), ends(k) = ud(15); end;
elseif strcmp(ohtype,'line')|strcmp(ohtype,'patch'), % it's a non-arrow line or
patch
convLineToPatch = 1; %set to make arrow patches when converting from lines.
if isinf(ispatch(k)), ispatch(k)=convLineToPatch|strcmp(ohtype,'patch'); end;
x=get(oh,'XData'); x=x(~isnan(x(:))); if isempty(x), x=NaN; end;
y=get(oh,'YData'); y=y(~isnan(y(:))); if isempty(y), y=NaN; end;
z=get(oh,'ZData'); z=z(~isnan(z(:))); if isempty(z), z=NaN; end;
start0 = [x(1) y(1) z(1) ];
stop0 = [x(end) y(end) z(end)];
else,
error([upper(mfilename) ' cannot convert ' ohtype ' objects.']);
end;
ii=find(isinf(start(k,:))); if ~isempty(ii), start(k,ii)=start0(ii); end;
ii=find(isinf(stop( k,:))); if ~isempty(ii), stop( k,ii)=stop0( ii); end;
end;
end;

% convert Inf's to NaN's


start( isinf(start )) = NaN;
stop( isinf(stop )) = NaN;
len( isinf(len )) = NaN;
baseangle( isinf(baseangle)) = NaN;
tipangle( isinf(tipangle )) = NaN;
wid( isinf(wid )) = NaN;
page( isinf(page )) = NaN;
crossdir( isinf(crossdir )) = NaN;
ends( isinf(ends )) = NaN;
ispatch( isinf(ispatch )) = NaN;

% set up the UserData data (here so not corrupted by log10's and such)
ud = [start stop len baseangle tipangle wid page crossdir ends];

% Set Page defaults


page = ~isnan(page) & trueornan(page);

% Get axes limits, range, min; correct for aspect ratio and log scale
axm = zeros(3,narrows);
axr = zeros(3,narrows);
axrev = zeros(3,narrows);
ap = zeros(2,narrows);
xyzlog = zeros(3,narrows);
limmin = zeros(2,narrows);
limrange = zeros(2,narrows);
oldaxlims = zeros(narrows,7);
oneax = all(ax==ax(1));
if (oneax),
T = zeros(4,4);
invT = zeros(4,4);
else,
T = zeros(16,narrows);
invT = zeros(16,narrows);
end;
axnotdone = logical(ones(size(ax)));
while (any(axnotdone)),
ii = min(find(axnotdone));
curax = ax(ii);
curpage = page(ii);
% get axes limits and aspect ratio
axl = [get(curax,'XLim'); get(curax,'YLim'); get(curax,'ZLim')];
oldaxlims(min(find(oldaxlims(:,1)==0)),:) = [curax reshape(axl',1,6)];
% get axes size in pixels (points)
u = get(curax,'Units');
axposoldunits = get(curax,'Position');
really_curpage = curpage & strcmp(u,'normalized');
if (really_curpage),
curfig = get(curax,'Parent');
pu = get(curfig,'PaperUnits');
set(curfig,'PaperUnits','points');
pp = get(curfig,'PaperPosition');
set(curfig,'PaperUnits',pu);
set(curax,'Units','pixels');
curapscreen = get(curax,'Position');
set(curax,'Units','normalized');
curap = pp.*get(curax,'Position');
else,
set(curax,'Units','pixels');
curapscreen = get(curax,'Position');
curap = curapscreen;
end;
set(curax,'Units',u);
set(curax,'Position',axposoldunits);
% handle non-stretched axes position
str_stretch = { 'DataAspectRatioMode' ; ...
'PlotBoxAspectRatioMode' ; ...
'CameraViewAngleMode' };
str_camera = { 'CameraPositionMode' ; ...
'CameraTargetMode' ; ...
'CameraViewAngleMode' ; ...
'CameraUpVectorMode' };
notstretched = strcmp(get(curax,str_stretch),'manual');
manualcamera = strcmp(get(curax,str_camera),'manual');
if ~arrow_WarpToFill(notstretched,manualcamera,curax),
% give a warning that this has not been thoroughly tested
if 0 & ARROW_STRETCH_WARN,
ARROW_STRETCH_WARN = 0;
strs = {str_stretch{1:2},str_camera{:}};
strs = [char(ones(length(strs),1)*sprintf('\n ')) char(strs)]';
warning([upper(mfilename) ' may not yet work quite right ' ...
'if any of the following are ''manual'':' strs(:).']);
end;
% find the true pixel size of the actual axes
texttmp = text(axl(1,[1 2 2 1 1 2 2 1]), ...
axl(2,[1 1 2 2 1 1 2 2]), ...
axl(3,[1 1 1 1 2 2 2 2]),'');
set(texttmp,'Units','points');
textpos = get(texttmp,'Position');
delete(texttmp);
textpos = cat(1,textpos{:});
textpos = max(textpos(:,1:2)) - min(textpos(:,1:2));
% adjust the axes position
if (really_curpage),
% adjust to printed size
textpos = textpos * min(curap(3:4)./textpos);
curap = [curap(1:2)+(curap(3:4)-textpos)/2 textpos];
else,
% adjust for pixel roundoff
textpos = textpos * min(curapscreen(3:4)./textpos);
curap = [curap(1:2)+(curap(3:4)-textpos)/2 textpos];
end;
end;
if ARROW_PERSP_WARN & ~strcmp(get(curax,'Projection'),'orthographic'),
ARROW_PERSP_WARN = 0;
warning([upper(mfilename) ' does not yet work right for 3-D perspective
projection.']);
end;
% adjust limits for log scale on axes
curxyzlog = [strcmp(get(curax,'XScale'),'log'); ...
strcmp(get(curax,'YScale'),'log'); ...
strcmp(get(curax,'ZScale'),'log')];
if (any(curxyzlog)),
ii = find([curxyzlog;curxyzlog]);
if (any(axl(ii)<=0)),
error([upper(mfilename) ' does not support non-positive limits on log-scaled
axes.']);
else,
axl(ii) = log10(axl(ii));
end;
end;
% correct for 'reverse' direction on axes;
curreverse = [strcmp(get(curax,'XDir'),'reverse'); ...
strcmp(get(curax,'YDir'),'reverse'); ...
strcmp(get(curax,'ZDir'),'reverse')];
ii = find(curreverse);
if ~isempty(ii),
axl(ii,[1 2])=-axl(ii,[2 1]);
end;
% compute the range of 2-D values
curT = get(curax,'Xform');
lim = curT*[0 1 0 1 0 1 0 1;0 0 1 1 0 0 1 1;0 0 0 0 1 1 1 1;1 1 1 1 1 1 1 1];
lim = lim(1:2,:)./([1;1]*lim(4,:));
curlimmin = min(lim')';
curlimrange = max(lim')' - curlimmin;
curinvT = inv(curT);
if (~oneax),
curT = curT.';
curinvT = curinvT.';
curT = curT(:);
curinvT = curinvT(:);
end;
% check which arrows to which cur corresponds
ii = find((ax==curax)&(page==curpage));
oo = ones(1,length(ii));
axr(:,ii) = diff(axl')' * oo;
axm(:,ii) = axl(:,1) * oo;
axrev(:,ii) = curreverse * oo;
ap(:,ii) = curap(3:4)' * oo;
xyzlog(:,ii) = curxyzlog * oo;
limmin(:,ii) = curlimmin * oo;
limrange(:,ii) = curlimrange * oo;
if (oneax),
T = curT;
invT = curinvT;
else,
T(:,ii) = curT * oo;
invT(:,ii) = curinvT * oo;
end;
axnotdone(ii) = zeros(1,length(ii));
end;
oldaxlims(oldaxlims(:,1)==0,:)=[];
% correct for log scales
curxyzlog = xyzlog.';
ii = find(curxyzlog(:));
if ~isempty(ii),
start( ii) = real(log10(start( ii)));
stop( ii) = real(log10(stop( ii)));
if (all(imag(crossdir)==0)), % pulled (ii) subscript on crossdir, 12/5/96 eaj
crossdir(ii) = real(log10(crossdir(ii)));
end;
end;

% correct for reverse directions


ii = find(axrev.');
if ~isempty(ii),
start( ii) = -start( ii);
stop( ii) = -stop( ii);
crossdir(ii) = -crossdir(ii);
end;

% transpose start/stop values


start = start.';
stop = stop.';

% take care of defaults, page was done above


ii=find(isnan(start(:) )); if ~isempty(ii), start(ii) = axm(ii)+axr(ii)/2;
end;
ii=find(isnan(stop(:) )); if ~isempty(ii), stop(ii) = axm(ii)+axr(ii)/2;
end;
ii=find(isnan(crossdir(:) )); if ~isempty(ii), crossdir(ii) = zeros(length(ii),1);
end;
ii=find(isnan(len )); if ~isempty(ii), len(ii) =
ones(length(ii),1)*deflen; end;
ii=find(isnan(baseangle )); if ~isempty(ii), baseangle(ii) =
ones(length(ii),1)*defbaseangle; end;
ii=find(isnan(tipangle )); if ~isempty(ii), tipangle(ii) =
ones(length(ii),1)*deftipangle; end;
ii=find(isnan(wid )); if ~isempty(ii), wid(ii) =
ones(length(ii),1)*defwid; end;
ii=find(isnan(ends )); if ~isempty(ii), ends(ii) =
ones(length(ii),1)*defends; end;

% transpose rest of values


len = len.';
baseangle = baseangle.';
tipangle = tipangle.';
wid = wid.';
page = page.';
crossdir = crossdir.';
ends = ends.';
ax = ax.';

% given x, a 3xN matrix of points in 3-space;


% want to convert to X, the corresponding 4xN 2-space matrix
%
% tmp1=[(x-axm)./axr; ones(1,size(x,1))];
% if (oneax), X=T*tmp1;
% else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=T.*tmp1;
% tmp2=zeros(4,4*N); tmp2(:)=tmp1(:);
% X=zeros(4,N); X(:)=sum(tmp2)'; end;
% X = X ./ (ones(4,1)*X(4,:));

% for all points with start==stop, start=stop-(verysmallvalue)*(up-direction);


ii = find(all(start==stop));
if ~isempty(ii),
% find an arrowdir vertical on screen and perpendicular to viewer
% transform to 2-D
tmp1 = [(stop(:,ii)-axm(:,ii))./axr(:,ii);ones(1,length(ii))];
if (oneax), twoD=T*tmp1;
else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=T(:,ii).*tmp1;
tmp2=zeros(4,4*length(ii)); tmp2(:)=tmp1(:);
twoD=zeros(4,length(ii)); twoD(:)=sum(tmp2)'; end;
twoD=twoD./(ones(4,1)*twoD(4,:));
% move the start point down just slightly
tmp1 = twoD + [0;-1/1000;0;0]*(limrange(2,ii)./ap(2,ii));
% transform back to 3-D
if (oneax), threeD=invT*tmp1;
else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=invT(:,ii).*tmp1;
tmp2=zeros(4,4*length(ii)); tmp2(:)=tmp1(:);
threeD=zeros(4,length(ii)); threeD(:)=sum(tmp2)'; end;
start(:,ii) = (threeD(1:3,:)./(ones(3,1)*threeD(4,:))).*axr(:,ii)+axm(:,ii);
end;

% compute along-arrow points


% transform Start points
tmp1=[(start-axm)./axr;ones(1,narrows)];
if (oneax), X0=T*tmp1;
else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=T.*tmp1;
tmp2=zeros(4,4*narrows); tmp2(:)=tmp1(:);
X0=zeros(4,narrows); X0(:)=sum(tmp2)'; end;
X0=X0./(ones(4,1)*X0(4,:));
% transform Stop points
tmp1=[(stop-axm)./axr;ones(1,narrows)];
if (oneax), Xf=T*tmp1;
else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=T.*tmp1;
tmp2=zeros(4,4*narrows); tmp2(:)=tmp1(:);
Xf=zeros(4,narrows); Xf(:)=sum(tmp2)'; end;
Xf=Xf./(ones(4,1)*Xf(4,:));
% compute pixel distance between points
D = sqrt(sum(((Xf(1:2,:)-X0(1:2,:)).*(ap./limrange)).^2));
D = D + (D==0); %eaj new 2/24/98
% compute and modify along-arrow distances
len1 = len;
len2 = len - (len.*tan(tipangle/180*pi)-wid/2).*tan((90-baseangle)/180*pi);
slen0 = zeros(1,narrows);
slen1 = len1 .* ((ends==2)|(ends==3));
slen2 = len2 .* ((ends==2)|(ends==3));
len0 = zeros(1,narrows);
len1 = len1 .* ((ends==1)|(ends==3));
len2 = len2 .* ((ends==1)|(ends==3));
% for no start arrowhead
ii=find((ends==1)&(D<len2));
if ~isempty(ii),
slen0(ii) = D(ii)-len2(ii);
end;
% for no end arrowhead
ii=find((ends==2)&(D<slen2));
if ~isempty(ii),
len0(ii) = D(ii)-slen2(ii);
end;
len1 = len1 + len0;
len2 = len2 + len0;
slen1 = slen1 + slen0;
slen2 = slen2 + slen0;
% note: the division by D below will probably not be accurate if both
% of the following are true:
% 1. the ratio of the line length to the arrowhead
% length is large
% 2. the view is highly perspective.
% compute stoppoints
tmp1=X0.*(ones(4,1)*(len0./D))+Xf.*(ones(4,1)*(1-len0./D));
if (oneax), tmp3=invT*tmp1;
else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=invT.*tmp1;
tmp2=zeros(4,4*narrows); tmp2(:)=tmp1(:);
tmp3=zeros(4,narrows); tmp3(:)=sum(tmp2)'; end;
stoppoint = tmp3(1:3,:)./(ones(3,1)*tmp3(4,:)).*axr+axm;
% compute tippoints
tmp1=X0.*(ones(4,1)*(len1./D))+Xf.*(ones(4,1)*(1-len1./D));
if (oneax), tmp3=invT*tmp1;
else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=invT.*tmp1;
tmp2=zeros(4,4*narrows); tmp2(:)=tmp1(:);
tmp3=zeros(4,narrows); tmp3(:)=sum(tmp2)'; end;
tippoint = tmp3(1:3,:)./(ones(3,1)*tmp3(4,:)).*axr+axm;
% compute basepoints
tmp1=X0.*(ones(4,1)*(len2./D))+Xf.*(ones(4,1)*(1-len2./D));
if (oneax), tmp3=invT*tmp1;
else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=invT.*tmp1;
tmp2=zeros(4,4*narrows); tmp2(:)=tmp1(:);
tmp3=zeros(4,narrows); tmp3(:)=sum(tmp2)'; end;
basepoint = tmp3(1:3,:)./(ones(3,1)*tmp3(4,:)).*axr+axm;
% compute startpoints
tmp1=X0.*(ones(4,1)*(1-slen0./D))+Xf.*(ones(4,1)*(slen0./D));
if (oneax), tmp3=invT*tmp1;
else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=invT.*tmp1;
tmp2=zeros(4,4*narrows); tmp2(:)=tmp1(:);
tmp3=zeros(4,narrows); tmp3(:)=sum(tmp2)'; end;
startpoint = tmp3(1:3,:)./(ones(3,1)*tmp3(4,:)).*axr+axm;
% compute stippoints
tmp1=X0.*(ones(4,1)*(1-slen1./D))+Xf.*(ones(4,1)*(slen1./D));
if (oneax), tmp3=invT*tmp1;
else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=invT.*tmp1;
tmp2=zeros(4,4*narrows); tmp2(:)=tmp1(:);
tmp3=zeros(4,narrows); tmp3(:)=sum(tmp2)'; end;
stippoint = tmp3(1:3,:)./(ones(3,1)*tmp3(4,:)).*axr+axm;
% compute sbasepoints
tmp1=X0.*(ones(4,1)*(1-slen2./D))+Xf.*(ones(4,1)*(slen2./D));
if (oneax), tmp3=invT*tmp1;
else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=invT.*tmp1;
tmp2=zeros(4,4*narrows); tmp2(:)=tmp1(:);
tmp3=zeros(4,narrows); tmp3(:)=sum(tmp2)'; end;
sbasepoint = tmp3(1:3,:)./(ones(3,1)*tmp3(4,:)).*axr+axm;

% compute cross-arrow directions for arrows with NormalDir specified


if (any(imag(crossdir(:))~=0)),
ii = find(any(imag(crossdir)~=0));
crossdir(:,ii) = cross((stop(:,ii)-start(:,ii))./axr(:,ii), ...
imag(crossdir(:,ii))).*axr(:,ii);
end;

% compute cross-arrow directions


basecross = crossdir + basepoint;
tipcross = crossdir + tippoint;
sbasecross = crossdir + sbasepoint;
stipcross = crossdir + stippoint;
ii = find(all(crossdir==0)|any(isnan(crossdir)));
if ~isempty(ii),
numii = length(ii);
% transform start points
tmp1 = [basepoint(:,ii) tippoint(:,ii) sbasepoint(:,ii) stippoint(:,ii)];
tmp1 = (tmp1-axm(:,[ii ii ii ii])) ./ axr(:,[ii ii ii ii]);
tmp1 = [tmp1; ones(1,4*numii)];
if (oneax), X0=T*tmp1;
else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=T(:,[ii ii ii ii]).*tmp1;
tmp2=zeros(4,16*numii); tmp2(:)=tmp1(:);
X0=zeros(4,4*numii); X0(:)=sum(tmp2)'; end;
X0=X0./(ones(4,1)*X0(4,:));
% transform stop points
tmp1 = [(2*stop(:,ii)-start(:,ii)-axm(:,ii))./axr(:,ii);ones(1,numii)];
tmp1 = [tmp1 tmp1 tmp1 tmp1];
if (oneax), Xf=T*tmp1;
else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=T(:,[ii ii ii ii]).*tmp1;
tmp2=zeros(4,16*numii); tmp2(:)=tmp1(:);
Xf=zeros(4,4*numii); Xf(:)=sum(tmp2)'; end;
Xf=Xf./(ones(4,1)*Xf(4,:));
% compute perpendicular directions
pixfact = ((limrange(1,ii)./limrange(2,ii)).*(ap(2,ii)./ap(1,ii))).^2;
pixfact = [pixfact pixfact pixfact pixfact];
pixfact = [pixfact;1./pixfact];
[dummyval,jj] = max(abs(Xf(1:2,:)-X0(1:2,:)));
jj1 = ((1:4)'*ones(1,length(jj))==ones(4,1)*jj);
jj2 = ((1:4)'*ones(1,length(jj))==ones(4,1)*(3-jj));
jj3 = jj1(1:2,:);
Xf(jj1)=Xf(jj1)+(Xf(jj1)-X0(jj1)==0); %eaj new 2/24/98
Xp = X0;
Xp(jj2) = X0(jj2) + ones(sum(jj2(:)),1);
Xp(jj1) = X0(jj1) - (Xf(jj2)-X0(jj2))./(Xf(jj1)-X0(jj1)) .* pixfact(jj3);
% inverse transform the cross points
if (oneax), Xp=invT*Xp;
else, tmp1=[Xp;Xp;Xp;Xp]; tmp1=invT(:,[ii ii ii ii]).*tmp1;
tmp2=zeros(4,16*numii); tmp2(:)=tmp1(:);
Xp=zeros(4,4*numii); Xp(:)=sum(tmp2)'; end;
Xp=(Xp(1:3,:)./(ones(3,1)*Xp(4,:))).*axr(:,[ii ii ii ii])+axm(:,[ii ii ii ii]);
basecross(:,ii) = Xp(:,0*numii+(1:numii));
tipcross(:,ii) = Xp(:,1*numii+(1:numii));
sbasecross(:,ii) = Xp(:,2*numii+(1:numii));
stipcross(:,ii) = Xp(:,3*numii+(1:numii));
end;

% compute all points


% compute start points
axm11 = [axm axm axm axm axm axm axm axm axm axm axm];
axr11 = [axr axr axr axr axr axr axr axr axr axr axr];
st = [stoppoint tippoint basepoint sbasepoint stippoint startpoint stippoint sbasepoint
basepoint tippoint stoppoint];
tmp1 = (st - axm11) ./ axr11;
tmp1 = [tmp1; ones(1,size(tmp1,2))];
if (oneax), X0=T*tmp1;
else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=[T T T T T T T T T T T].*tmp1;
tmp2=zeros(4,44*narrows); tmp2(:)=tmp1(:);
X0=zeros(4,11*narrows); X0(:)=sum(tmp2)'; end;
X0=X0./(ones(4,1)*X0(4,:));
% compute stop points
tmp1 = ([start tipcross basecross sbasecross stipcross stop stipcross sbasecross
basecross tipcross start] ...
- axm11) ./ axr11;
tmp1 = [tmp1; ones(1,size(tmp1,2))];
if (oneax), Xf=T*tmp1;
else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=[T T T T T T T T T T T].*tmp1;
tmp2=zeros(4,44*narrows); tmp2(:)=tmp1(:);
Xf=zeros(4,11*narrows); Xf(:)=sum(tmp2)'; end;
Xf=Xf./(ones(4,1)*Xf(4,:));
% compute lengths
len0 = len.*((ends==1)|(ends==3)).*tan(tipangle/180*pi);
slen0 = len.*((ends==2)|(ends==3)).*tan(tipangle/180*pi);
le = [zeros(1,narrows) len0 wid/2 wid/2 slen0 zeros(1,narrows) -slen0 -wid/2 -wid/2
-len0 zeros(1,narrows)];
aprange = ap./limrange;
aprange = [aprange aprange aprange aprange aprange aprange aprange aprange aprange
aprange aprange];
D = sqrt(sum(((Xf(1:2,:)-X0(1:2,:)).*aprange).^2));
Dii=find(D==0); if ~isempty(Dii), D=D+(D==0); le(Dii)=zeros(1,length(Dii)); end; %should
fix DivideByZero warnings
tmp1 = X0.*(ones(4,1)*(1-le./D)) + Xf.*(ones(4,1)*(le./D));
% inverse transform
if (oneax), tmp3=invT*tmp1;
else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=[invT invT invT invT invT invT invT invT invT
invT invT].*tmp1;
tmp2=zeros(4,44*narrows); tmp2(:)=tmp1(:);
tmp3=zeros(4,11*narrows); tmp3(:)=sum(tmp2)'; end;
pts = tmp3(1:3,:)./(ones(3,1)*tmp3(4,:)) .* axr11 + axm11;

% correct for ones where the crossdir was specified


ii = find(~(all(crossdir==0)|any(isnan(crossdir))));
if ~isempty(ii),
D1 = [pts(:,1*narrows+ii)-pts(:,9*narrows+ii) ...
pts(:,2*narrows+ii)-pts(:,8*narrows+ii) ...
pts(:,3*narrows+ii)-pts(:,7*narrows+ii) ...
pts(:,4*narrows+ii)-pts(:,6*narrows+ii) ...
pts(:,6*narrows+ii)-pts(:,4*narrows+ii) ...
pts(:,7*narrows+ii)-pts(:,3*narrows+ii) ...
pts(:,8*narrows+ii)-pts(:,2*narrows+ii) ...
pts(:,9*narrows+ii)-pts(:,1*narrows+ii)]/2;
ii = ii'*ones(1,8) + ones(length(ii),1)*[1:4 6:9]*narrows;
ii = ii(:)';
pts(:,ii) = st(:,ii) + D1;
end;

% readjust for reverse directions


iicols=(1:narrows)'; iicols=iicols(:,ones(1,11)); iicols=iicols(:).';
tmp1=axrev(:,iicols);
ii = find(tmp1(:)); if ~isempty(ii), pts(ii)=-pts(ii); end;

% readjust for log scale on axes


tmp1=xyzlog(:,iicols);
ii = find(tmp1(:)); if ~isempty(ii), pts(ii)=10.^pts(ii); end;

% compute the x,y,z coordinates of the patches;


ii = narrows*(0:10)'*ones(1,narrows) + ones(11,1)*(1:narrows);
ii = ii(:)';
x = zeros(11,narrows);
y = zeros(11,narrows);
z = zeros(11,narrows);
x(:) = pts(1,ii)';
y(:) = pts(2,ii)';
z(:) = pts(3,ii)';

% do the output
if (nargout<=1),
% % create or modify the patches
newpatch = trueornan(ispatch) & (isempty(oldh)|~strcmp(get(oldh,'Type'),'patch'));
newline = ~trueornan(ispatch) & (isempty(oldh)|~strcmp(get(oldh,'Type'),'line'));
if isempty(oldh), H=zeros(narrows,1); else, H=oldh; end;
% % make or modify the arrows
for k=1:narrows,
if all(isnan(ud(k,[3 6])))&arrow_is2DXY(ax(k)), zz=[]; else, zz=z(:,k); end;
xx=x(:,k); yy=y(:,k);
if (0), % this fix didn't work, so let's not use it -- 8/26/03
% try to work around a MATLAB 6.x OpenGL bug -- 7/28/02
mask=any([ones(1,2+size(zz,2));diff([xx yy zz],[],1)],2);
xx=xx(mask); yy=yy(mask); if ~isempty(zz), zz=zz(mask); end;
end;
% plot the patch or line
xyz = {'XData',xx,'YData',yy,'ZData',zz,'Tag',ArrowTag};
if newpatch(k)|newline(k),
if newpatch(k),
H(k) = patch(xyz{:});
else,
H(k) = line(xyz{:});
end;
if ~isempty(oldh), arrow_copyprops(oldh(k),H(k)); end;
else,
if ispatch(k), xyz={xyz{:},'CData',[]}; end;
set(H(k),xyz{:});
end;
end;
if ~isempty(oldh), delete(oldh(oldh~=H)); end;
% % additional properties
set(H,'Clipping','off');
set(H,{'UserData'},num2cell(ud,2));
if (length(extraprops)>0), set(H,extraprops{:}); end;
% handle choosing arrow Start and/or Stop locations if unspecified
[H,oldaxlims,errstr] = arrow_clicks(H,ud,x,y,z,ax,oldaxlims);
if ~isempty(errstr), error([upper(mfilename) ' got ' errstr]); end;
% set the output
if (nargout>0), h=H; end;
% make sure the axis limits did not change
if isempty(oldaxlims),
ARROW_AXLIMITS = [];
else,
lims = get(oldaxlims(:,1),{'XLim','YLim','ZLim'})';
lims = reshape(cat(2,lims{:}),6,size(lims,2));
mask = arrow_is2DXY(oldaxlims(:,1));
oldaxlims(mask,6:7) = lims(5:6,mask)';
ARROW_AXLIMITS = oldaxlims(find(any(oldaxlims(:,2:7)'~=lims)),:);
if ~isempty(ARROW_AXLIMITS),
warning(arrow_warnlimits(ARROW_AXLIMITS,narrows));
end;
end;
else,
% don't create the patch, just return the data
h=x;
yy=y;
zz=z;
end;

function out = arrow_defcheck(in,def,prop)


% check if we got 'default' values
out = in;
if ~isstr(in), return; end;
if size(in,1)==1 & strncmp(lower(in),'def',3),
out = def;
elseif ~isempty(prop),
error([upper(mfilename) ' does not recognize ''' in(:)' ''' as a valid ''' prop '''
string.']);
end;
function [H,oldaxlims,errstr] = arrow_clicks(H,ud,x,y,z,ax,oldaxlims)
% handle choosing arrow Start and/or Stop locations if necessary
errstr = '';
if isempty(H)|isempty(ud)|isempty(x), return; end;
% determine which (if any) need Start and/or Stop
needStart = all(isnan(ud(:,1:3)'))';
needStop = all(isnan(ud(:,4:6)'))';
mask = any(needStart|needStop);
if ~any(mask), return; end;
ud(~mask,:)=[]; ax(:,~mask)=[];
x(:,~mask)=[]; y(:,~mask)=[]; z(:,~mask)=[];
% make them invisible for the time being
set(H,'Visible','off');
% save the current axes and limits modes; set to manual for the time being
oldAx = gca;
limModes=get(ax(:),{'XLimMode','YLimMode','ZLimMode'});
set(ax(:),{'XLimMode','YLimMode','ZLimMode'},{'manual','manual','manual'});
% loop over each arrow that requires attention
jj = find(mask);
for ii=1:length(jj),
h = H(jj(ii));
axes(ax(ii));
% figure out correct call
if needStart(ii), prop='Start'; else, prop='Stop'; end;
[wasInterrupted,errstr] = arrow_click(needStart(ii)&needStop(ii),h,prop,ax(ii));
% handle errors and control-C
if wasInterrupted,
delete(H(jj(ii:end)));
H(jj(ii:end))=[];
oldaxlims(jj(ii:end),:)=[];
break;
end;
end;
% restore the axes and limit modes
axes(oldAx);
set(ax(:),{'XLimMode','YLimMode','ZLimMode'},limModes);

function [wasInterrupted,errstr] = arrow_click(lockStart,H,prop,ax)


% handle the clicks for one arrow
fig = get(ax,'Parent');
% save some things
oldFigProps = {'Pointer','WindowButtonMotionFcn','WindowButtonUpFcn'};
oldFigValue = get(fig,oldFigProps);
oldArrowProps = {'EraseMode'};
oldArrowValue = get(H,oldArrowProps);
set(H,'EraseMode','background'); %because 'xor' makes shaft invisible unless Width>1
global ARROW_CLICK_H ARROW_CLICK_PROP ARROW_CLICK_AX ARROW_CLICK_USE_Z
ARROW_CLICK_H=H; ARROW_CLICK_PROP=prop; ARROW_CLICK_AX=ax;
ARROW_CLICK_USE_Z=~arrow_is2DXY(ax)|~arrow_planarkids(ax);
set(fig,'Pointer','crosshair');
% set up the WindowButtonMotion so we can see the arrow while moving around
set(fig,'WindowButtonUpFcn','set(gcf,''WindowButtonUpFcn'','''')', ...
'WindowButtonMotionFcn','');
if ~lockStart,
set(H,'Visible','on');
set(fig,'WindowButtonMotionFcn',[mfilename '(''callback'',''motion'');']);
end;
% wait for the button to be pressed
[wasKeyPress,wasInterrupted,errstr] = arrow_wfbdown(fig);
% if we wanted to click-drag, set the Start point
if lockStart & ~wasInterrupted,
pt = arrow_point(ARROW_CLICK_AX,ARROW_CLICK_USE_Z);
feval(mfilename,H,'Start',pt,'Stop',pt);
set(H,'Visible','on');
ARROW_CLICK_PROP='Stop';
set(fig,'WindowButtonMotionFcn',[mfilename '(''callback'',''motion'');']);
% wait for the mouse button to be released
try
waitfor(fig,'WindowButtonUpFcn','');
catch
errstr = lasterr;
wasInterrupted = 1;
end;
end;
if ~wasInterrupted, feval(mfilename,'callback','motion'); end;
% restore some things
set(gcf,oldFigProps,oldFigValue);
set(H,oldArrowProps,oldArrowValue);

function arrow_callback(varargin)
% handle redrawing callbacks
if nargin==0, return; end;
str = varargin{1};
if ~isstr(str), error([upper(mfilename) ' got an invalid Callback command.']); end;
s = lower(str);
if strcmp(s,'motion'),
% motion callback
global ARROW_CLICK_H ARROW_CLICK_PROP ARROW_CLICK_AX ARROW_CLICK_USE_Z

feval(mfilename,ARROW_CLICK_H,ARROW_CLICK_PROP,arrow_point(ARROW_CLICK_AX,ARROW_CLICK_USE_Z)
);
drawnow;
else,
error([upper(mfilename) ' does not recognize ''' str(:).' ''' as a valid Callback
option.']);
end;

function out = arrow_point(ax,use_z)


% return the point on the given axes
if nargin==0, ax=gca; end;
if nargin<2, use_z=~arrow_is2DXY(ax)|~arrow_planarkids(ax); end;
out = get(ax,'CurrentPoint');
out = out(1,:);
if ~use_z, out=out(1:2); end;

function [wasKeyPress,wasInterrupted,errstr] = arrow_wfbdown(fig)


% wait for button down ignoring object ButtonDownFcn's
if nargin==0, fig=gcf; end;
errstr = '';
% save ButtonDownFcn values
objs = findobj(fig);
buttonDownFcns = get(objs,'ButtonDownFcn');
mask=~strcmp(buttonDownFcns,''); objs=objs(mask); buttonDownFcns=buttonDownFcns(mask);
set(objs,'ButtonDownFcn','');
% save other figure values
figProps = {'KeyPressFcn','WindowButtonDownFcn'};
figValue = get(fig,figProps);
% do the real work
set(fig,'KeyPressFcn','set(gcf,''KeyPressFcn'','''',''WindowButtonDownFcn'','''');', ...
'WindowButtonDownFcn','set(gcf,''WindowButtonDownFcn'','''')');
lasterr('');
try
waitfor(fig,'WindowButtonDownFcn','');
wasInterrupted = 0;
catch
wasInterrupted = 1;
end
wasKeyPress = ~wasInterrupted & strcmp(get(fig,'KeyPressFcn'),'');
if wasInterrupted, errstr=lasterr; end;
% restore ButtonDownFcn and other figure values
set(objs,'ButtonDownFcn',buttonDownFcns);
set(fig,figProps,figValue);

function [out,is2D] = arrow_is2DXY(ax)


% check if axes are 2-D X-Y plots
% may not work for modified camera angles, etc.
out = logical(zeros(size(ax))); % 2-D X-Y plots
is2D = out; % any 2-D plots
views = get(ax(:),{'View'});
views = cat(1,views{:});
out(:) = abs(views(:,2))==90;
is2D(:) = out(:) | all(rem(views',90)==0)';

function out = arrow_planarkids(ax)


% check if axes descendents all have empty ZData (lines,patches,surfaces)
out = logical(ones(size(ax)));
allkids = get(ax(:),{'Children'});
for k=1:length(allkids),
kids = get([findobj(allkids{k},'flat','Type','line')
findobj(allkids{k},'flat','Type','patch')
findobj(allkids{k},'flat','Type','surface')],{'ZData'});
for j=1:length(kids),
if ~isempty(kids{j}), out(k)=logical(0); break; end;
end;
end;

function arrow_fixlimits(axlimits)
% reset the axis limits as necessary
if isempty(axlimits), disp([upper(mfilename) ' does not remember any axis limits to
reset.']); end;
for k=1:size(axlimits,1),
if any(get(axlimits(k,1),'XLim')~=axlimits(k,2:3)),
set(axlimits(k,1),'XLim',axlimits(k,2:3)); end;
if any(get(axlimits(k,1),'YLim')~=axlimits(k,4:5)),
set(axlimits(k,1),'YLim',axlimits(k,4:5)); end;
if any(get(axlimits(k,1),'ZLim')~=axlimits(k,6:7)),
set(axlimits(k,1),'ZLim',axlimits(k,6:7)); end;
end;

function out = arrow_WarpToFill(notstretched,manualcamera,curax)


% check if we are in "WarpToFill" mode.
out = strcmp(get(curax,'WarpToFill'),'on');
% 'WarpToFill' is undocumented, so may need to replace this by
% out = ~( any(notstretched) & any(manualcamera) );

function out = arrow_warnlimits(axlimits,narrows)


% create a warning message if we've changed the axis limits
msg = '';
switch (size(axlimits,1))
case 1, msg='';
case 2, msg='on two axes ';
otherwise, msg='on several axes ';
end;
msg = [upper(mfilename) ' changed the axis limits ' msg ...
'when adding the arrow'];
if (narrows>1), msg=[msg 's']; end;
out = [msg '.' sprintf('\n') ' Call ' upper(mfilename) ...
' FIXLIMITS to reset them now.'];

function arrow_copyprops(fm,to)
% copy line properties to patches
props = {'EraseMode','LineStyle','LineWidth','Marker','MarkerSize',...
'MarkerEdgeColor','MarkerFaceColor','ButtonDownFcn', ...
'Clipping','DeleteFcn','BusyAction','HandleVisibility', ...
'Selected','SelectionHighlight','Visible'};
lineprops = {'Color', props{:}};
patchprops = {'EdgeColor',props{:}};
patch2props = {'FaceColor',patchprops{:}};
fmpatch = strcmp(get(fm,'Type'),'patch');
topatch = strcmp(get(to,'Type'),'patch');
set(to( fmpatch& topatch),patch2props,get(fm( fmpatch& topatch),patch2props)); %p->p
set(to(~fmpatch&~topatch),lineprops, get(fm(~fmpatch&~topatch),lineprops )); %l->l
set(to( fmpatch&~topatch),lineprops, get(fm( fmpatch&~topatch),patchprops )); %p->l
set(to(~fmpatch& topatch),patchprops, get(fm(~fmpatch&
topatch),lineprops) ,'FaceColor','none'); %l->p

function arrow_props
% display further help info about ARROW properties
c = sprintf('\n');
disp([c ...
'ARROW Properties: Default values are given in [square brackets], and other' c ...
' acceptable equivalent property names are in (parenthesis).' c c ...
' Start The starting points. For N arrows, B' c ...
' this should be a Nx2 or Nx3 matrix. /|\ ^' c ...
' Stop The end points. For N arrows, this /|||\ |' c ...
' should be a Nx2 or Nx3 matrix. //|||\\ L|' c ...
' Length Length of the arrowhead (in pixels on ///|||\\\ e|' c ...
' screen, points on a page). [16] (Len) ////|||\\\\ n|' c ...
' BaseAngle Angle (degrees) of the base angle /////|D|\\\\\ g|' c ...
' ADE. For a simple stick arrow, use //// ||| \\\\ t|' c ...
' BaseAngle=TipAngle. [90] (Base) /// ||| \\\ h|' c ...
' TipAngle Angle (degrees) of tip angle ABC. //<----->|| \\ |' c ...
' [16] (Tip) / base ||| \ V' c ...
' Width Width of the base in pixels. Not E angle ||<-------->C' c ...
' the ''LineWidth'' prop. [0] (Wid) |||tipangle' c ...
' Page If provided, non-empty, and not NaN, |||' c ...
' this causes ARROW to use hardcopy |||' c ...
' rather than onscreen proportions. A' c ...
' This is important if screen aspect --> <-- width' c ...
' ratio and hardcopy aspect ratio are ----CrossDir---->' c ...
' vastly different. []' c...
' CrossDir A vector giving the direction towards which the fletches' c ...
' on the arrow should go. [computed such that it is perpen-' c ...
' dicular to both the arrow direction and the view direction' c ...
' (i.e., as if it was pasted on a normal 2-D graph)] (Note' c ...
' that CrossDir is a vector. Also note that if an axis is' c ...
' plotted on a log scale, then the corresponding component' c ...
' of CrossDir must also be set appropriately, i.e., to 1 for' c ...
' no change in that direction, >1 for a positive change, >0' c ...
' and <1 for negative change.)' c ...
' NormalDir A vector normal to the fletch direction (CrossDir is then' c ...
' computed by the vector cross product [Line]x[NormalDir]). []' c ...
' (Note that NormalDir is a vector. Unlike CrossDir,' c ...
' NormalDir is used as is regardless of log-scaled axes.)' c ...
' Ends Set which end has an arrowhead. Valid values are ''none'',' c ...
' ''stop'', ''start'', and ''both''. [''stop''] (End)' c...
' ObjectHandles Vector of handles to previously-created arrows to be' c ...
' updated or line objects to be converted to arrows.' c ...
' [] (Object,Handle)' c ]);

function out = arrow_demo


% demo
% create the data
[x,y,z] = peaks;
[ddd,out.iii]=max(z(:));
out.axlim = [min(x(:)) max(x(:)) min(y(:)) max(y(:)) min(z(:)) max(z(:))];

% modify it by inserting some NaN's


[m,n] = size(z);
m = floor(m/2);
n = floor(n/2);
z(1:m,1:n) = NaN*ones(m,n);

% graph it
clf('reset');
out.hs=surf(x,y,z);
out.x=x; out.y=y; out.z=z;
xlabel('x'); ylabel('y');

function h = arrow_demo3(in)
% set the view
axlim = in.axlim;
axis(axlim);
zlabel('z');
%set(in.hs,'FaceColor','interp');
view(3); % view(viewmtx(-37.5,30,20));
title(['Demo of the capabilities of the ARROW function in 3-D']);

% Normal blue arrow


h1 = feval(mfilename,[axlim(1) axlim(4) 4],[-.8 1.2 4], ...
'EdgeColor','b','FaceColor','b');

% Normal white arrow, clipped by the surface


h2 = feval(mfilename,axlim([1 4 6]),[0 2 4]);
t=text(-2.4,2.7,7.7,'arrow clipped by surf');

% Baseangle<90
h3 = feval(mfilename,[3 .125 3.5],[1.375 0.125 3.5],30,50);
t2=text(3.1,.125,3.5,'local maximum');

% Baseangle<90, fill and edge colors different


h4 = feval(mfilename,axlim(1:2:5)*.5,[0 0 0],36,60,25, ...
'EdgeColor','b','FaceColor','c');
t3=text(axlim(1)*.5,axlim(3)*.5,axlim(5)*.5-.75,'origin');
set(t3,'HorizontalAlignment','center');

% Baseangle>90, black fill


h5 = feval(mfilename,[-2.9 2.9 3],[-1.3 .4 3.2],30,120,[],6, ...
'EdgeColor','r','FaceColor','k','LineWidth',2);
% Baseangle>90, no fill
h6 = feval(mfilename,[-2.9 2.9 1.3],[-1.3 .4 1.5],30,120,[],6, ...
'EdgeColor','r','FaceColor','none','LineWidth',2);

% Stick arrow
h7 = feval(mfilename,[-1.6 -1.65 -6.5],[0 -1.65 -6.5],[],16,16);
t4=text(-1.5,-1.65,-7.25,'global mininum');
set(t4,'HorizontalAlignment','center');

% Normal, black fill


h8 = feval(mfilename,[-1.4 0 -7.2],[-1.4 0 -3],'FaceColor','k');
t5=text(-1.5,0,-7.75,'local minimum');
set(t5,'HorizontalAlignment','center');

% Gray fill, crossdir specified, 'LineStyle' --


h9 = feval(mfilename,[-3 2.2 -6],[-3 2.2 -.05],36,[],27,6,[],[0 -1 0], ...
'EdgeColor','k','FaceColor',.75*[1 1 1],'LineStyle','--');

% a series of normal arrows, linearly spaced, crossdir specified


h10y=(0:4)'/3;
h10 = feval(mfilename,[-3*ones(size(h10y)) h10y -6.5*ones(size(h10y))], ...
[-3*ones(size(h10y)) h10y -.05*ones(size(h10y))], ...
12,[],[],[],[],[0 -1 0]);

% a series of normal arrows, linearly spaced


h11x=(1:.33:2.8)';
h11 = feval(mfilename,[h11x -3*ones(size(h11x)) 6.5*ones(size(h11x))], ...
[h11x -3*ones(size(h11x)) -.05*ones(size(h11x))]);

% series of magenta arrows, radially oriented, crossdir specified


h12x=2; h12y=-3; h12z=axlim(5)/2; h12xr=1; h12zr=h12z; ir=.15;or=.81;
h12t=(0:11)'/6*pi;
h12 = feval(mfilename, ...
[h12x+h12xr*cos(h12t)*ir h12y*ones(size(h12t)) ...
h12z+h12zr*sin(h12t)*ir],[h12x+h12xr*cos(h12t)*or ...
h12y*ones(size(h12t)) h12z+h12zr*sin(h12t)*or], ...
10,[],[],[],[], ...
[-h12xr*sin(h12t) zeros(size(h12t)) h12zr*cos(h12t)],...
'FaceColor','none','EdgeColor','m');

% series of normal arrows, tangentially oriented, crossdir specified


or13=.91; h13t=(0:.5:12)'/6*pi;
locs = [h12x+h12xr*cos(h13t)*or13 h12y*ones(size(h13t)) h12z+h12zr*sin(h13t)*or13];
h13 = feval(mfilename,locs(1:end-1,:),locs(2:end,:),6);

% arrow with no line ==> oriented downwards


h14 = feval(mfilename,[3 3 .100001],[3 3 .1],30);
t6=text(3,3,3.6,'no line'); set(t6,'HorizontalAlignment','center');

% arrow with arrowheads at both ends


h15 = feval(mfilename,[-.5 -3 -3],[1 -3 -3],'Ends','both','FaceColor','g', ...
'Length',20,'Width',3,'CrossDir',[0 0 1],'TipAngle',25);

h=[h1;h2;h3;h4;h5;h6;h7;h8;h9;h10;h11;h12;h13;h14;h15];

function h = arrow_demo2(in)
axlim = in.axlim;
dolog = 1;
if (dolog), set(in.hs,'YData',10.^get(in.hs,'YData')); end;
shading('interp');
view(2);
title(['Demo of the capabilities of the ARROW function in 2-D']);
hold on; [C,H]=contour(in.x,in.y,in.z,20,'-'); hold off;
for k=H',
set(k,'ZData',(axlim(6)+1)*ones(size(get(k,'XData'))),'Color','k');
if (dolog), set(k,'YData',10.^get(k,'YData')); end;
end;
if (dolog), axis([axlim(1:2) 10.^axlim(3:4)]); set(gca,'YScale','log');
else, axis(axlim(1:4)); end;

% Normal blue arrow


start = [axlim(1) axlim(4) axlim(6)+2];
stop = [in.x(in.iii) in.y(in.iii) axlim(6)+2];
if (dolog), start(:,2)=10.^start(:,2); stop(:,2)=10.^stop(:,2); end;
h1 = feval(mfilename,start,stop,'EdgeColor','b','FaceColor','b');

% three arrows with varying fill, width, and baseangle


start = [-3 -3 10; -3 -1.5 10; -1.5 -3 10];
stop = [-.03 -.03 10; -.03 -1.5 10; -1.5 -.03 10];
if (dolog), start(:,2)=10.^start(:,2); stop(:,2)=10.^stop(:,2); end;
h2 = feval(mfilename,start,stop,24,[90;60;120],[],
[0;0;4],'Ends',str2mat('both','stop','stop'));
set(h2(2),'EdgeColor',[0 .35 0],'FaceColor',[0 .85 .85]);
set(h2(3),'EdgeColor','r','FaceColor',[1 .5 1]);
h=[h1;h2];

function out = trueornan(x)


if isempty(x),
out=x;
else,
out = isnan(x);
out(~out) = x(~out);
end;

ELIPSOID
clear all
clc
syms x y z
a=2;
b=2;
c=3;
phi=0:0.1:2*pi+0.1;
theta=-pi/2:0.1:pi/2+0.1;
[phi theta]=meshgrid(phi,theta);%chia luoi
x=a*cos(phi).*cos(theta);
y=b*sin(phi).*cos(theta);
z=c*sin(theta);
surfc(x,y,z)
xlabel('Truc Ox')
ylabel('Truc Oy')
zlabel('Truc Oz')
title('Do thi Paraboloid eliptic: x^2/a^2+z^2/b^2+z^2/c^2=1')
rotate3d on

HYPERBOLOID 1 TẦNG
clear all
clc
syms x y z
a=3;
b=4;
c=2;
r=3;
r=1:0.1:r;
phi=0:0.1:2*pi+0.1;
[r phi]=meshgrid(r,phi);%chia luoi
x=a*r.*cos(phi);
y=b*r.*sin(phi);
z1=sqrt((r.^2-1)*c^2);
z2=-sqrt((r.^2-1)*c^2);
surf(x,y,z1)
hold on
surf(x,y,z2)
xlabel('Truc Ox')
ylabel('Truc Oy')
zlabel('Truc Oz')
title('Do thi hyperboloid 1 tang: x^2/a^2+y^2/b^2-z^2/c^2=1')
rotate3d on
hold off

HYPERBOLOID 2 TẦNG
clear all
clc
syms x y z real
a=3;
b=4;
c=2;
r=3;
r=0:0.1:r;
phi=0:0.1:2*pi+0.1;
[r phi]=meshgrid(r,phi);%chia luoi
x=a*r.*cos(phi);
y=b*r.*sin(phi);
z1=sqrt((r.^2+1))*c;
z2=-sqrt((r.^2+1))*c;
surf(x,y,z1)
hold on
surf(x,y,z2)
xlabel('Truc Ox')
ylabel('Truc Oy')
zlabel('Truc Oz')
title('Do thi hyperboloid 2 tang: x^2/a^2+y^2/b^2-z^2/c^2=-1')
rotate3d on
hold off

NÓN 2 PHÍA
clear all
clc
syms x y z
a=3;
b=4;
c=4;
r=0:0.1:1;
phi=0:0.1:2*pi+0.1;
[r phi]=meshgrid(r,phi);%chia luoi
x=a*r.*cos(phi);
y=b*r.*sin(phi);
z1=r*c;
z2=-r*c;
surfc(x,y,z1)
hold on
surfc(x,y,z2)
xlabel('Truc Ox')
ylabel('Truc Oy')
zlabel('Truc Oz')
title('Do thi Paraboloid eliptic: y=x^2/a^2+z^2/b^2')
rotate3d on
hold off
PARABOLOID ELIPTIC
clear all
clc
syms x y
a=1;
b=2;
r=2*norm([a b]);
r=0:0.1:r;
phi=0:0.1:2*pi+0.1;
[r phi]=meshgrid(r,phi);%chia luoi
x=r.*cos(phi);
y=r.*sin(phi);
z=x.^2/(a^2)+y.^2/(b^2);
surfc(x,y,z)
xlabel('Truc Ox')
ylabel('Truc Oy')
zlabel('Truc Oz')
title('Do thi Paraboloid eliptic: z=x^2/a^2+y^2/b^2')
rotate3d on

PARABOLOID ELIPTIC 2:
clear all
clc
syms x y z
a=1;
b=1;
r=2*norm([a b]);
r=0:0.1:r;
phi=0:0.1:2*pi+0.1;
[r phi]=meshgrid(r,phi);%chia luoi
x=r.*cos(phi);
z=r.*sin(phi);
y=x.^2/(a^2)+z.^2/(b^2);
surfc(x,y,z)
xlabel('Truc Ox')
ylabel('Truc Oy')
zlabel('Truc Oz')
title('Do thi Paraboloid eliptic: y=x^2/a^2+z^2/b^2')
rotate3d on

PARABOLOID HYPERBOLIC
clear all
clc
syms x y z
a=3;
b=4;
x=-3*a:0.5:3*a;
y=-3*b:0.5:3*b;
[x y]=meshgrid(x,y);%chia luoi
z=x.^2/(a^2)-y.^2/(b^2);
surfc(x,y,z)
xlabel('Truc Ox')
ylabel('Truc Oy')
zlabel('Truc Oz')
title('Do thi Paraboloid eliptic: z=x^2/a^2-y^2/b^2')
rotate3d on

PARABOLOID HYPERBOLIC 2:
clear all
clc
syms x y z
a=1;
b=1;
x=-3*a:0.3:3*a;
z=-3*b:0.3:3*b;
[x z]=meshgrid(x,z);%chia luoi
y=z.^2/(a^2)-x.^2/(b^2);
surfc(x,y,z)
xlabel('Truc Ox')
ylabel('Truc Oy')
zlabel('Truc Oz')
title('Do thi Paraboloid eliptic: y=z^2-y^2')
rotate3d on

TRỤ ELIPSE
clear all
clc
syms x y z
a=3;
b=4;
z=norm([a b]);
r=-1:0.1:1;
phi=0:0.1:2*pi+0.1;
[z phi]=meshgrid(z*r,phi);%chia luoi
x=a*cos(phi);
y=b*sin(phi);
surfc(x,y,z)
xlabel('Truc Ox')
ylabel('Truc Oy')
zlabel('Truc Oz')
title('Do thi Tru elipsoid: x^2/a^2+z^2/b^2=1')
rotate3d on

TRỤ PARABOLIC
clear all
clc
clf
syms x y z
a=2;
x=-a:0.1:2;
z=-a:0.1:a;
[z x]=meshgrid(z,x);%chia luoi
y=x.^2;
surfc(x,y,z)
xlabel('Truc Ox')
ylabel('Truc Oy')
zlabel('Truc Oz')
title('Do thi Tru parabol: y=x^2')
rotate3d on

MỘT SỐ HÀM VẼ
CONE:
function cone(a,b,c);
% cone(a,b) ve non x^2/a^2+y^2/b^2=z^2/c^2 (non chinh tac)trong toa do tru
clc
clf
phi=linspace(0,2*pi,50);
r=linspace(0,1,50);
[r phi]=meshgrid(r,phi);%tao luoi theo goc va ban kinh thiet dien.
x=a*r.*cos(phi);%x tinh theo toa do tru (cuc)
y=b*r.*sin(phi);%y tinh theo toa do tru (cuc)
z=c*r;% pt mat non tren, -z la mat non duoi
%lenh ve mat cong, mau luoi mat dinh la black,trong hinh mau luoi la white
%('none' la ve khong luoi)
%do trong suot la 0.5
surf(x,y,z,'FaceColor','r','EdgeColor','white','FaceAlpha',0.2);
hold on
%lenh ve theo luoi,
mesh(x,y,-z,'EdgeColor','m','FaceAlpha',0.5);
axis square
rotate3d on% lenh quay hinh trong khong gian

CONE 1:
function cone1(a,b,c)
%cone1(a,b,c) la lenh ve non x^2/a^2+y^2/b^2=z^2/c^2 (non chinh tac)
clc,clf;
x=linspace(-a,a,50);
y=linspace(-b,b,50);
[x y]=meshgrid(x,y);% ham tao luoi
z=c*sqrt(x.^2/a^2+y.^2/b^2);%z la non tren, -z la non duoi
surf(x,y,z,'FaceColor','red');
hold on
mesh(x,y,-z,'FaceColor','red');
rotate3d on

CYLINDERD:
function cylinderd(a,b,zmin,zmax)
%cylinderd(a,b,zmin,zmax)la lenh ve tru x^2/a^2+y^2/b^2=1
%zmin,zmax la can chay cua z(chieu cao cua tru)
phi=linspace(0,2*pi,50);
h=linspace(zmin,zmax,50);
[phi h]=meshgrid(phi,h);
x=a*cos(phi);
y=b*sin(phi);
z=h;
surfc(x,y,z,'FaceColor','r','EdgeColor','none','FaceAlpha',0.5);
rotate3d on

ELIPPSOID
function elippsoid(a,b,c)
%elippsoid(a,b,c) la lenh ve elippsoid x^2/a^2+y^2/b^2+z^2/c^2 =1 trong
%toa do cau
clf
phi=linspace(0,2*pi,50);
theta=linspace(0,pi,50);
[phi theta]=meshgrid(phi,theta);
x=a*cos(phi).*sin(theta);
y=b*sin(phi).*sin(theta);
z=c*cos(theta);
surf(x,y,z,'FaceColor','cyan','FaceAlpha',0.5,'EdgeColor','white');
rotate3d on

ĐẠI SỐ
CƠ SỞ:
function coso
A=input('nhap khong gian AX=0: ');
[~,n]=size(A);
disp(['so chieu cua AX=0 la: ' num2str(n-rank(A))])
if ~isempty(null(A))
disp('co so khong gian nghiem cua AX=0: ')
disp(null(A)')
end

CHÉO HÓA:
function cheohoa
A=input('nhap ma tran A=');
[a,b]=size(A);
while a~=b
disp('Ma tran A khong vuong')
A=input('nhap lai ma tran A=');
[a,b]=size(A);
end
syms x
lamda=solve(det(A-x*eye(size(A))));
lamda=double(lamda);
i=1;
while i<=length(lamda) %loai nghiem phuc
if abs(imag(lamda(i)))>0.000001
lamda(i)=[];
i=i-1;
else
lamda(i)=lamda(i)-imag(lamda(i))*1i;
end
i=i+1;
end
lamda=unique(lamda);
[n,~]=size(lamda);
P=[];
for i=1:n
P=[null(A-lamda(i)*eye(a)) P];
end
[~,n]=size(P);
if a~=n
disp('khong cheo hoa ma tran A duoc')
return
end
D=P\A*P;
D(abs(D)<0.00001)=0;
disp('ma tran cheo hoa cua A la:')
disp(D)
end

CHUYỂN CƠ SỞ:
function chuyencs
E=input('nhap ma tran E: ');%nhap cs E
[m,n]=size(E); %tim kich thuoc ma tran E
while m~=n || rank(E)~=n %xem E co phai cs ko
disp('E khong phai la co so')
E=input('nhap lai ma tran E: ');
[m,n]=size(E);
end
F=input('nhap ma tran F: ');%nhap ma tran F
[a,b]=size(F);
while b~=rank(F) || a~=b || a~=m
disp('F khong phai la co so')
F=input('nhap lai ma tran F: ');
[a,b]=size(F);
end
X=F/E; %tim ma tran toa do cua F trong E
X=X';% chuyen vi ma tran X
disp('ma tran chuyen co so E sang F la:')
disp(X)
end
ĐA THỨC:
function dathuc
syms x
f=input('nhap ham f(x)= ');
a=input('nhap ma tran A= ');
[m,n]=size(a);
while m~=n
disp('A khong vuong, nhao lai')
a=input('nhap ma tran A= ');
[m,n]=size(a);
end
g=f;i=1;
while ~isreal(g)
g=limit(f/x^i,x,inf); %tim he so cua fx, vidu: f= 2*x^3 3*x^2 + x - 4, he so o day la 2;
i=i+1;
end
t=solve(f);
t=sym2poly(t);
t=poly(t);
t(abs(t)<0.000001)=0;
[~,n]=size(t);
t=t(1,n:-1:1);
p=eye(m)*t(1,1);
for i=2:n
z=t(1,i);
for j=1:i-1 %tinh a luy thua (giao vien ko cho dung ham a^b)
z=z*a;
end
p=p+z;
end
p=double(g*p);
disp(' p(A)= ')
disp(p)
end

ĐỊNH THỨC SƠ CẤP:


function dinhthucsc
a=input('nhap ma tran vao ');
[m,n]=size(a);
l=0;
k=1;
det=1;
if m~=n
disp('ma tran khong vuong')
else
for i=1:n
[a,l]=sapxep(a,i,l);
if a(i,i)~=0
k=k*a(i,i);
a(i,: )=a(i,: )/a(i,i);
else
det=0;
break
end
for j=m:-1:i+1
a(j,: )=a(j,: )-a(i,: )*a(j,i);
end
end
det=det*(-1)^l*k;
disp('dinh thuc cau ma tran la: ')
disp(det)
end
end
%ham sap xep cho a(i,i) khac 0
function [x,l]=sapxep(a,i,l)
[m,~]=size(a);
j=i+1;
while j<=m
if a(i,i)==0
n=a(i,: );
a(i,: )=a(j,: );
a(j,: )=n;
j=j+1;
l=l+1;
else
break
end
end
x=a;
end

GIẢI HỆ:
function giaihe
A=input('nhap ma tran A= ');
[ma,na]=size(A);
b=input('nhap ma tran cot b= ');
[mb,nb]=size(b);
while nb~=1 && mb~=ma
disp('nhap sai b, yeu cau nhap lai')
b=input('nhap ma tran cot b= ');
end
if hang(A)~=hang([A b])
disp('he vo nghiem')
return
end
if hang(A)==na
disp('he co nghiem duy nhat la:')
disp((A\b)')
else
disp('he AX=b vo so nghiem')
disp('he vo so nghiem, co so khong gian nghiemcua AX=0: ')
disp(null(A)')
disp('mot nghiem rieng cua he AX=b la:')
B=[A b];B=matranbt(B);
k=hang(B);
for i=ma:-1:k+1
B(i,:)=[];
end
A=B(:,1:na);
b=B(:,na+1);
x=[];
for i=1:na-k
b=b-A(:,i);
A(:,i)=[];
x=[x 1];
end
disp([x (A\b)'])
end
end
%tim hang cua ma tran
function x=hang(A)
A=matranbt(A);
[m,n]=size(A);
k=0;
if n>m
k=n-m;
end
for i=1:m
if A(i,:)==zeros(1,n)
k=k+1;
end
end
x=n-k;
end
%dua ve ma tran bac thang
function x=matranbt(a)
[m,~]=size(a );
for i=1:m
[a]=sapxep(a,i);
if a(i,i)~=0
a(i,: )=a(i,: )/a(i,i);
for j=m:-1:i+1
a(j,: )=a(j,: )-a(i,: )*a(j,i);
end
end
end
x=a;
end
%ham sap xep cot cua ma tran tang dan
function x=sapxep(a,i)
[m,~]=size(a);
j=i+1;
while j<=m
if a(i,i)==0
n=a(i,: );
a(i,: )=a(j,: );
a(j,: )=n;
j=j+1;
else
break
end
end
x=a;
end

HẠNG:
function hang
A=input('nhap ma tran A= ');
A=matranbt(A);
[m,n]=size(A);
k=0;
if n>m
k=n-m;
end
for i=1:m
if A(i,:)==zeros(1,n)
k=k+1;
end
end
disp(['hang cua A= ' num2str(n-k)])
end
%dua ve ma tran bac thang
function x=matranbt(a)
[m,~]=size(a );
for i=1:m
[a]=sapxep(a,i);
if a(i,i)~=0
a(i,: )=a(i,: )/a(i,i);
for j=m:-1:i+1
a(j,: )=a(j,: )-a(i,: )*a(j,i);
end
end
end
x=a;
end
%ham sap xep cot cua ma tran tang dan
function x=sapxep(a,i)
[m,~]=size(a);
j=i+1;
while j<=m
if a(i,i)==0
n=a(j,: );
a(i,: )=a(j,: );
a(i,: )=n;
j=j+1;
else
break
end
end
x=a;
end

HÌNH CHIẾU:
function hinhchieu
f=input('nhap khong gian con F: ');
v=input('nhap vector x: ');
[m,n]=size(f);[~,nv]=size(v);
if n~=nv
disp('ban nhap sai vector, xin kiem tra lai')
else
matrix=zeros(m); %tao ma tran 0 co m hang, m cot
for i=1:m
for j=1:m
matrix(i,j)=tichvohuong(f(i,:),f(j,:));
end
end
exp=zeros(m,1);
for i=1:m
exp(i,1)=tichvohuong(v,f(i,:));%phan ma tran mo rong
end
x=matrix\exp;
prfv=zeros(1,n);
for i=1:m
prfv=prfv+x(i,1)*f(i,:);
end
disp('hinh chieu cua x xuong F la vetor: ')
disp(prfv)
end
end
%ham tinh tich vo huong
function a=tichvohuong(f1,f2)
[~,n]=size(f1);
a=0;
for i=1:n
a=a+f1(1,i)*f2(1,i);
end
end

KHOẢNG CÁCH:
function khoangcach
syms x
F=input('nhap khong gian vector con F: '); %nhap luon ca x vd:[x^4+7*x^3-3*x^2-x+7;x^3-
6*x^2+5*x-9]
[m,~]=size(F);
if m==1
F=F';
end
f=input('nhap vector f: '); %vd:[4*x^4-4*x+8]
disp('tich phan di tu');
a=input('a= ');b=input('b= ');
k=bac(F);p=bac(f);
n=max(k,p); %tim bac cao nhat cua da thuc vd x^5 --> bac 5
Fc=chuyendt(F,n,m); % chuyen sang dang ma tran vd:[4 1 5...]
%-------------khong gian con F nhap vao chua chac da la co so--> chuyen F thanh cs
r=rank(Fc); %tim hang cua F
if m~=r %neu F phu thuoc tuyen tinh
Fc=rref(Fc); %dua ve ma tran co so (no khong lam thay doi khong gian con)
for i=r+1:m %bo di nhung vector phu thuoc tuyen tinh
Fc(i,:)=[];
end
end
if n+1==r % neu khong gian F chinh la co so cua khong gian V
disp('f nam trong khong gian F => d(f,F)=0')
else
F=chuyen(Fc,r); %chuyen F ve dang da thuc vd:[3*x^2+7*x^2-x+7;....]
z=length(F); %F co z vector
%------------thuat toan tim vector hinh chieu giong trong sach sgk
A=zeros(z);
for i=1:z
A(i,1:z)=int(F(i)*(F(1:z)),a,b);
end
exp=zeros(length(F),1);
for i=1:z
exp(i)=int(f*F(i),a,b);
end
t=A\exp;
%t la toa do hinh chieu cua f trong F
prfF=0; prfF=sym(prfF);
for i=1:length(F) %tu toa do t, ta tim vector hinh chieu
prfF=prfF+t(i)*F(i);
end
k=f-prfF; % toa do [f - ( hinh chieu prfF )] chinh la vector khoang cach
kc=sqrt(int(k*k,x,a,b)); %tinh do dai vector kc = can bac 2 cua tich vo huong
kc=double(kc);
disp('khang cach tu f den khong gian con F bang: ')
disp(kc)
end
end
%tim bac cua x trong khong khong gian vector
function k=bac(f)
syms x
[m,~]=size(f);
k=0;
for i=1:m
while ~isreal(limit(f(i,1)/x^k,x,inf))
k=k+1;
end
end
end
%chuyen khong gian vector da thuc ve khong gian vector thuong
function k=chuyendt(f,n,m)
s=zeros(m,n+1);
for i=1:m
s(i,:)=[zeros(1,n-bac(f(i))) sym2poly(f(i))];
end
k=s;
end
%chuyen khong gian vector thuong ve khong gian vector da thuc
function k=chuyen(f,m)
syms x
k=zeros(m,1);k=sym(k);
for i=1:m
k(i)=poly2sym(f(i,:));
end
end

MA TRẬN BẬC THANG:


function matranbt
a=input('nhap ma tran vao ');
[m,n]=size(a );
for i=1:min(m,n)
[a]=sapxep(a,i);
if a(i,i)~=0
a(i,: )=a(i,: )/a(i,i);
for j=m:-1:i+1
a(j,: )=a(j,: )-a(i,: )*a(j,i);
end
end
end
disp('ma tran bac thang la: ')
disp(a)
end
%ham sap xep a(i,i) ~=0
function x=sapxep(a,i)
[m,~]=size(a);
j=i+1;
while j<=m
if a(i,i)==0
n=a(i,: );
a(i,: )=a(j,: );
a(j,: )=n;
j=j+1;
else
break
end
end
x=a;
end

MA TRẬN TUYẾN TÍNH:


function matrantt
E=input('nhap ma tran cs E= ');
[m,n]=size(E);
while rank(E)~=n || m~=n
disp('E khong phai la cs, yeu cau nhap lai')
E=input('nhap lai ma tran cs E= ');
[m,n]=size(E);
end
A=input('nhap ma tran tuyen tinh A trong cs E' );
while size(E)~=size(A)
disp('A khong phai la ma tran tuyen tinh trong cs E, yeu cau nhap lai')
A=input('nhap lai ma tran tuyen tinh A=');
end
B=input('nhap ma tran B= ');
[m,n]=size(B);
while rank(B)~=n || m~=n
disp('B khong phai la cs, yeu cau nhap lai')
B=input('nhap lai ma tran cs B= ');
[m,n]=size(B);
end
while size(B)~=size(E)
disp('ma tran B khong tuong thich voi ma tran A, yeu cau nhap lai')
B=input('nhap ma tran cs B=');
end
Xbe=B/E;%toa do cua cs B trong cs E
Xie=A*Xbe';%toa do anh cua cs B trong cs E
X=Xie'*E;%toa do anh cua cs B
Xbb=X/B;%toa do anh cua cs B trong cs B
Xbb=Xbb';% chuyen thanh ma tran anh xa tuyen tinh trong cs B
disp('ma tran anh xa tuyen tinh trong cs B la:')
disp(Xbb)
end

NGHỊCH ĐẢO:
function nghichdao
A=input('nhap ma tran A= ');
[m,n]=size(A);
if m~=n
disp('ma tran khong vuong')
else
d=det(A);
if d == 0
disp('ma tran suy bien')
else
for i=1:m
for j=1:n
B=A;
B(:,j)=[];
B(i,:)=[];
C(i,j)=((-1)^(i+j))*det(B);
end
end
C=C';
X=C/d;
disp('ma tran nghich dao cua A la')
disp(X)
end
end
end

NGHỊCH ĐẢO SƠ CẤP:


function nghichdaosc
a=input('nhap ma tran vao ');
[m,n]=size(a);
if m~=n
disp('ma tran khong vuong')
elseif det(a)==0
disp('ma tran suy bien, khong co ma tran nghich dao')
else
I=eye(size(a));
for i=1:n
[a,I]=sapxep(a,i,I);
I(i,: )=I(i,: )/a(i,i);
a(i,: )=a(i,: )/a(i,i);
for j=m:-1:i+1
I(j,: )=I(j,: )-I(i,: )*a(j,i);
a(j,: )=a(j,: )-a(i,: )*a(j,i);
end
end
for i=n:-1:1
[a,I]=sapxep(a,i,I);
I(i,: )=I(i,: )/a(i,i);
a(i,: )=a(i,: )/a(i,i);
for j=1:i-1
I(j,: )=I(j,: )-I(i,: )*a(j,i);
a(j,: )=a(j,: )-a(i,: )*a(j,i);
end
end
disp('ma tran nghich dao la: ')
disp(I)
end
end
%ham sap xep cot cua ma tran tang dan
function [x,k]=sapxep(a,i,I)
[m,~]=size(a);
j=i;
while j<=m
if a(i,i)==0
n=a(i,: ); N=I(i,: );
a(i,: )=a(j,: ); I(i,: )=I(j,: );
a(j,: )=n; I(j,: )=N;
j=j+1;
else
break
end
end
x=a;
k=I;
end

PHỤ HỢP:
function phuhop
A=input('nhap ma tran A= ');
C=zeros(size(A));
[m,n]=size(A);
if m~=n
disp('ma tran A khong vuong')
return
end
for i=1:m
for j=1:n
B=A;
B(:,j)=[];
B(i,:)=[];
C(i,j)=((-1)^(i+j))*det(B);
end
end
C=C';
disp('ma tran phu hop cua A la:')
disp(C)
end

TOÀN PHƯƠNG:
function toanphuong
A=input('nhap ma tran toan phuong A= ');
[a b]=size(A);
while a~=b
disp('ma tran A khong vuong')
A=input('nhap lai ma tran toan phuong A= ');
[a b]=size(A);
end
while ~isequal(A,A')
disp('ma tran A khong doi xung')
disp(A)
A=input('nhap lai ma tran toan phuong A= ');
end
d=eig(A);d=unique(d);
disp('cac lamda cua A la:')
disp(d')
if isempty(d(d<=0))
disp('ma tran toan phuong A xac dinh duong')
elseif isempty(d(d>=0))
disp('ma tran toan phuong A xac dinh am')
elseif isempty(d(d>0)) && ~isempty(d(d==0)) && ~isempty(d(d<0))
disp('ma tran toan phuong A nua xac dinh am')
elseif isempty(d(d<0)) && ~isempty(d(d==0)) && ~isempty(d(d>0))
disp('ma tran toan phuong A nua xac dinh duong')
else
disp('ma tran toan phuong A khong xac dinh duong cung khong xac dinh duong')
end
end

TRỰC CHUẨN:
function tracchuan
f=input('nhap khong gian con F: ');
[m,~]=size(f);
if rank(f)~=m
disp('ma tran phu thuoc tuyfn tinh')
return
end
fc=zeros(size(f));
fc(1,:)=f(1,:);
if m==1
fc=fc/(sqrt(f*f'));
else
alpha=zeros(m-1,1);
for i=1:m-1
fc(i+1,:)=f(i+1,:);
for j=1:i
alpha(j,1)=(f(i+1,:)*fc(j,:)')/(fc(j,:)*fc(j,:)');
fc(i+1,:)=fc(i+1,:)-alpha(j,1)*fc(j,:);
end
end
for i=1:m
fc(i,:)=fc(i,:)/(sqrt(fc(i,:)*fc(i,:)'));
end
end
disp('ho truc giao Gram-Schmidt:')
disp(fc)
end

TRỊ RIÊNG:
function tririeng
A=input('nhap ma tran A=');
[a,b]=size(A);
if a~=b
fprintf('Ma tran A khong vuong')
else
syms x
lamda=solve(det(A-x*eye(size(A))));
lamda=double(lamda);
lamda=unique(lamda); %loai bo nghiem trung nhau
i=1;
while i<=length(lamda) %loai nghiem phuc
if abs(imag(lamda(i)))>0.000001
lamda(i)=[];
i=i-1;
else
lamda(i)=lamda(i)-imag(lamda(i))*1i;
end
i=i+1;
end
disp('cac tri rieng cua A la:')
disp(lamda')
[n,~]=size(lamda);
disp('co so cua cac khong gian con rieng:')
for i=1:n
disp(['voi lamda= ' num2str(lamda(i)) ':'])
disp(null(A-lamda(i)*eye(a))')
end
end

XÁC ĐỊNH:
function xacdinh
a=input('nhap ma tran A= ');
[m,n]=size(a);
while m~=n
disp('ma tran A ko vuong, yeu cau nhap lai: ')
a=input('nhap ma tran A= ');
[m,n]=size(a);
end
for i=1:m
b=a(1:i,1:i);
d(i,1)=det(b);
end
d=double(d);
disp ('cac dinh thuc duong cheo la')
disp(d)
b=d(d<=0);
if isempty(b)
disp('a xac dinh duong')
else
disp('a khong xac dinh duong')
end
end

XÓA:
function xoa
a=input('nhap a=');
b=input('nhap ma tran cac cot can xoa: ');
b=unique(b);[~,m]=size(b);
for i=m:-1:1
if b(i)<=length(a)
a(:,b(i))=[];
end
end
disp(a)

CƠ SỞ ẢNH:
function [C DIM]= cosoanh(A, B)
[n, ~]= size(A);
C= rref(B, n- rank(B));
C= C(1:rank(A), :);
DIM= rank(B);
end

CỞ SỞ NHÂN:
function [C DIM]= cosonhan(A, B)
[n, ~]= size(A);
E= [];
for i= 1: n
D= rref([A, B(:, i)]);
E=[E; D(:, n +1)'];
end
C= null(E);
C= 1/min(abs((C)))*C*sign(C(1));
DIM= rank(C);
end

You might also like