Documentos de Académico
Documentos de Profesional
Documentos de Cultura
Ejercicios Resueltos Matlab
Ejercicios Resueltos Matlab
NACIONAL
“HERMILIO VALDIZÁN MEDRANO”
HUÁNUCO
Facultad de Ingeniería Industrial y Sistemas
E.A.P. Ingeniería Industrial
MÉTODOS NUMÉRICOS.
EJERCICIO 1
x01=[-1 -1 1 1];
y01=[0 1 1 0];
x02=[0 0.5 0 0.5 0 0 0 0.5 1 1];
y02=[1 0.5 0 0.5 1 2.25 1.5 1.25 1.25 1];
h=pi/10;
t=0:h:2*pi;
t01=0.5*sin(t)+1;
t02=0.5*cos(t);
t03=0.5*sin(t)-1;
t04=0.5*cos(t);
t05=0.25*sin(t);
t06=0.25*cos(t)+2.5;
plot(x01,y01,'linewidth',3,'color','k')
axis([-2 2 -1 4])
grid on
hold on
plot (x02,y02,'linewidth',4)
plot (t01,t02,'color','k','linewidth',3)
plot (t03,t04,'color','k','linewidth',3)
plot (t05,t06,'color','b','linewidth',3)
colormap('spring')
title('METODOS NUMERICOS FIIS UNHEVAL 2014 ,QUISPE ZEVALLOS,
DEISY','color','b')
EJERCICIO 2
%ciclista
x1=[-1 -1 1 1];
y1=[0 1 1 0];
x2=[0 -0.5 0 -0.5 0 0 0 -0.5 -1 -1];
y2=[1 0.5 0 0.5 1 2.25 1.5 1.25 1.25 1];
h=pi/10;
t=0:h:2*pi;
t1= 0.5*sin(t)+1;
t2= 0.5*cos(t);
t3= 0.5*sin(t)-1;
t4= 0.5*cos(t);
t5= 0.25*sin(t);
t6=0.25*cos(t)+2.5;
plot(x1,y1,'linewidth',3,'color','k')
axis([-2 2 -1 4])
grid on
hold on
plot(x2,y2,'linewidth',4)
plot(t1,t2,'color','k','linewidth',3)
plot(t3,t4,'color','k','linewidth',3)
plot(t5,t6,'color','k','linewidth',3)
EJERCICIO 3
hr=pi/30;
t=0:hr:2*pi;
x0=cos(t);y0=0*t;z0=sin(t);
%rueda numero 1%
x1=(x0-2);y1=(y0-1);z1=z0;
%rueda delantera numero 2%
x2=(0.6*x0+2);y2=(y0-1);z2=0.6*z0;
%rueda numero 3%
x3=(x0-2);y3=(y0+1);z3=z0;
%rueda numero 4%
x4=(0.6*x0+2);y4=(y0+1);z4=0.6*z0;
x5=0.3*x0-1;y5=y0;z5=(0.5*z0+3);
plot3(x1,y1,z1,'linewidth',3,'color','k')
axis([-5 5 -4 4 -2 6])
grid on
hold on
plot3(x2,y2,z2,'linewidth',3,'color','k')
plot3(x3,y3,z3,'linewidth',3,'color','k')
plot3(x4,y4,z4,'linewidth',3,'color','k')
%lineas 4 de la cuTRIMOTO%
y6=[-1 1 -0.5 -0.5 0.5 0.5 0.5 -0.5 -0.5 -0.5 -0.5 -0.5 0.5 0.5 -0.5 -0.5 0.5 0.5 0.5 0.5
0.5 0.5 0.5 -0.5 -0.5 -0.5 -0.5];
x6=[-2 -2 -2 -2 -2 -2 2 2 -2 -2 0.3 0 0 0.3 0.3 -2 -2 0 0.3 0 -2 -2 -2 -2 -2 0 -2];
z6=[0 0 0 1 1 0 0 0 0 1 1 0 0 1 1 1 1 1 1 1 1.5 1 1.5 1.5 1 1 1.5];
%lineas 2 de la cuatrimoto%
y7=[-1 1 -0.5 0 0.5 0 -0.5 -0.5 -0.5 0.5 0.5];
x7=[2 2 2 1 2 1 1 1 1 1 1];
z7=[0 0 0 1.5 0 1.5 1.5 1.7 1.5 1.5 1.7];
%cuerpo%
x8=[0 1 0 1 -1 -1 -1 0.5 1 0.5 0 0.5 1];
y8=[0.5 0 -0.5 0 0 0 0 0.5 0.5 0.5 0 -0.5 -0.5];
z8=[0 1 0 1 1 2.5 2 1 1.7 1 2 1 1.7];
%sombrero%
x9=3*[-0.23 -0.2 0.2 0.23 -0.23 -0.1 -0.1 0.1 0.1 ]-1;
y9=3*[0 0 0 0 0 0 0 0 0];
z9=3*[1.05 0.9 0.9 1.05 1.05 1.05 1.15 1.15 1.05]+0.5;
plot3(x6,y6,z6,'linewidth',3,'color','r')
plot3(x7,y7,z7,'linewidth',3,'color','k')
plot3(x8,y8,z8,'linewidth',4,'color',[0 0 1])
patch(x5,y5,z5,[1 0.5 0.5])
patch(x9,y9,z9,[0 1 1])
title('metodos numericos fiis unheval 2015 GIOVANA INGA RIXI','color','r')
hold off
EJERCICIO 4
%calcular logaritmo de los 10 numeros primos
a=1; b=3; c=5; d=7; e=11; f=13;g=17;
l1= log(a);l2=log(b);l3=log(c);
disp('EL RESULTADO ES:')
disp(l1),disp(l2),disp(l3)
suma=l1+l2+l3;
disp('LA SUMA ES:')
disp(suma)
EJERCICIO 5
x1=[-12 -5 0 -5 -12 -5 0 -1 2 -1 0 -1 2 -1 0 2 5 2 0 2 5];
x12=[-11 -4 0 -4 -11 -4 0 1 -2 1 0 1 -2 1 0 2 5 2 0 2 5];
y1=[-3 -5 0 5 3 5 0 -3 -7 -3 0 3 7 3 0 -3 -2 -3 0 3 2];
z1=[-1 1 -1 1 -1 1 -1 1 -1 1 -1 1 -1 1 -1 1 -1 1 -1 1 -1 ];
hhh= pi/10;
u= 0:hhh:pi*2;
v= 0:hhh:pi;
nv= length(v) ;nu= length(u);
ya=sin(v);
ya=ya';
za=cos(v');
zb=za;
for i=2:nu
za=[za zb];
end
t1=5*ya*cos(u)-5;
t2=4*ya*sin(u);
t2z=za;
surf (t1,t2,t2z)
t3=2*ya*cos(u)+2;
t4=2*ya*sin(u);
t4z=za;
hold on
surf (t3,t4,t4z)
plot3(x1,y1,z1,'linewidth',3,'color','k')
title('METODOS NUMERICOS FIIS UNHEVAL 2014','color', 'r')
xlabel('datos para x araña 3d','color','b')
ylabel('datos para y araña 3d','color','b')
zlabel('datos para z araña 3d','color','b')
view([130.7 7.3])
colormap(gray)
axis([-12 12 -8 8 -1 8])
grid on
EJERCICIO 6
EJERCICIO 7
x1=[-12 -5 0 -5 -12 -5 0 -1 2 -1 0 -1 2 -1 0 2 5 2 0 2 5];
x12=[-11 -4 0 -4 -11 -4 0 1 -2 1 0 1 -2 1 0 2 5 2 0 2 5];
y1=[-3 -5 0 5 3 5 0 -3 -7 -3 0 3 7 3 0 -3 -2 -3 0 3 2];
z1=[-1 1 -1 1 -1 1 -1 1 -1 1 -1 1 -1 1 -1 1 -1 1 -1 1 -1 ];
hhh= pi/10;
u= 0:hhh:pi*2;
v= 0:hhh:pi;
nv= length(v) ;nu= length(u);
ya=sin(v);
ya=ya';
za=cos(v');
zb=za;
for i=2:nu
za=[za zb];
end
t1=5*ya*cos(u)-5;
t2=4*ya*sin(u);
t2z=za;
surf (t1,t2,t2z)
t3=2*ya*cos(u)+2;
t4=2*ya*sin(u);
t4z=za;
hold on
surf (t3,t4,t4z)
plot3(x1,y1,z1,'linewidth',3,'color','k')
title('METODOS NUMERICOS FIIS UNHEVAL 2014','color', 'r')
xlabel('datos para x araña 3d','color','b')
ylabel('datos para y araña 3d','color','b')
zlabel('datos para z araña 3d','color','b')
view([130.7 7.3])
colormap(colorcube)
axis([-12 12 -8 8 -1 8])
grid on
EJERCICIO 8
x1=[-12 -5 0 -5 -12 -5 0 -1 2 -1 0 -1 2 -1 0 2 5 2 0 2 5];
x12=[-11 -4 0 -4 -11 -4 0 1 -2 1 0 1 -2 1 0 2 5 2 0 2 5];
y1=[-3 -5 0 5 3 5 0 -3 -7 -3 0 3 7 3 0 -3 -2 -3 0 3 2];
z1=[-1 1 -1 1 -1 1 -1 1 -1 1 -1 1 -1 1 -1 1 -1 1 -1 1 -1 ];
hhh= pi/10;
u= 0:hhh:pi*2;
v= 0:hhh:pi;
nv= length(v) ;nu= length(u);
ya=sin(v);
ya=ya';
za=cos(v');
zb=za;
for i=2:nu
za=[za zb];
end
t1=5*ya*cos(u)-5;
t2=4*ya*sin(u);
t2z=za;
surf (t1,t2,t2z)
t3=2*ya*cos(u)+2;
t4=2*ya*sin(u);
t4z=za;
hold on
surf (t3,t4,t4z)
plot3(x1,y1,z1,'linewidth',3,'color','k')
title('METODOS NUMERICOS FIIS UNHEVAL 2014','color', 'r')
xlabel('datos para x araña 3d','color','b')
ylabel('datos para y araña 3d','color','b')
zlabel('datos para z araña 3d','color','b')
view([130.7 7.3])
colormap(flag)
axis([-12 12 -8 8 -1 8])
grid on
EJERCICIO 9
ARAÑA BIDIMENCIONAL
t=0:0.6:6.3;
t1=5*cos(t)-5;
t2=4*sin(t);
patch(t1,t2,[0.9 0.9 0.9])
grid on
axis([-15 10 -10 10])
t3=2*cos(t)+2;
t4=2*sin(t);
hold on
patch(t3,t4,[0.9 0.9 0.9])
x1=[-12 -5 0 -5 -12 -5 0 -1 2 -1 0 -1 2 -1 0 2 5 2 0 2 5];
x12=[-11 -4 0 -4 -11 -4 0 1 -2 1 0 1 -2 1 0 2 5 2 0 2 5];
y1=[-3 -5 0 5 3 5 0 -3 -7 -3 0 3 7 3 0 -3 -2 -3 0 3 2];
plot(x1,y1,'linewidth',3,'color','b')
%al colocar ':ok' las patas de la araña se esconden detras del cuerpo%
xlabel('DATOS X PARA EL GRAFICO','color','r')
ylabel('DATOS y PARA EL GRAFICO','color','r')
title('METODOS NUMERICOS FIIS UNEHVAL 2014 ARAÑA','color','y')
EJERCICIO 10
IMAGEN 3D
function cine11
axis off;
m=moviein(30);
for n=1:30
xa=-2:0.2:2;
ya=-2:0.2:2;
[x,y]=meshgrid(xa,ya);
z=x.^2-y.^2+y;
surf(z);
title('METODOS NUMERICOS 2014 FIIS UNHEVAL','color','R')
view([-37.5+6*n 30]);
axis([0 25 0 30 -44]);
axis off;
m(:,n)=getframe;
end
movie(m,60,10)
EJERCICIO 11
CINE EN MOVIMIENTO
function cine11giovanapag148
axis off;
m=moviein(100);
for n=1:30
xa=-2:0.2:2;
ya=-2:0.2:2;
[x,y]=meshgrid(xa,ya);
z=x.^2-y.^2+y;
surf(z);
title('METODOS NUMERICOS 2014 FIIS UNHEVAL','color','R')
view([-37.5+6*n 30]);
axis([0 25 0 30 -4 4]);
axis off;
m(:,n)=getframe;
end
movie(m,60,10)
EJERCICIO 12
ENGRANAJE
clear
clc
va=input('ingrese vueltas de A:...');
da=input('ingrese dientes de A:...');
vb=input('ingrese vueltas de B:...');
db=input('ingrese dientes de B:...');
%para que me halle el valor de las vueltas de A, le pongo el valor CERO
%porque no podemos calcular ningun valor cuando le pongamos cero a las
vueltas
%es como decir (0==??)
if (va==0)
va=(vb*db)/da;
disp('el valor de las vueltas de A es:...')
disp(va)
plot(va)
%para hallar el valor los dientes de A, le pongo 1
%porque no vamos a encontrar ningun engranaje de un solo diente
%es como decir (1==??)
elseif (da==1)
da=(vb*db)/va;
disp('el valor de los dientes de A es:...')
disp(da)
plot(da)
%para que me halle el valor de las vueltas de B, le pongo el valor CERO
%porque no podemos calcular ningun valor cuando le pongamos cero a las
vueltas
%es como decir (0==??)
elseif (vb==0)
vb=(va*da)/db;
disp('el valor de las vueltas de B es:...')
disp(vb)
plot(vb)
%para hallar el valor los dientes de B, le pongo 1
%porque no vamos a encontrar ningun engranaje de un solo diente
%es como decir (1==??)
else (db==1)
db=(va*da)/vb;
disp('el valor de los dientes de B es:...')
disp(db)
plot(db)
end
EJERCICIO 13
EXPONENCIAL
clc
x=1:001:5
f=exp(x)
plot(x,f)
title('funcion exponencial')
xlabel('x')
ylabel('exp(x)')
grid on
x=0:pi/2;
Xa=atan(4/2);
Xb=pi+atan(4/2);
disp('Puntos');
disp(Xa);
disp(Xb);
fx=Xa:0.01:Xb;
Y1=2*sin(fx);
Y2=4*cos(fx);
hold on
plot(fx,Y1)
plot(fx,Y2)
hold off
EN MOVIMIENTO
function pruebagiovana
M=moviein(10)%se usa para dar movimiento a la figura%;
x=[-2*pi:0.02:2*pi];
for j=1:10
y=cos(x+j*pi/8)+tan(j/2*pi);
plot(x,y,'linewidth',2,'color','r');
title('METODOS NUMERICOS FIIS UNHEVAL 2014 PAGINA 147','color','b');
xlabel('datos para x','color','r');
ylabel('datos para y','color','r');
M(:,j)=getframe;
end
movie(M,10,15)
EJERCICIO 16
EN MOVIMIENTO
function usobar
M=moviein(10)%se usa para dar movimiento a la figura%;
x=[-2*pi:0.2:2*pi];
for j=1:10000
y=sec(x+j*pi/8)+sin(j/2*pi)*sin(x)+56;
plot(x,y,'linewidth',2,'color','k');
title('METODOS NUMERICOS ','color','c');
xlabel('datos para x','color','r');
ylabel('datos para y','color','r');
M(:,j)=getframe;
end
movie(M,10,15)
EJERCICIO 17
CARGA ELÉCTRICA
clc;
global f;
fprintf('Fuerza electrica para una distribucion discreta de carga \n');
fprintf('teniendo en cuenta que se encuentran en el vacio \n\n\n');
n=input('ingrese nuemro de cargas puntuales:');
q0=input('ingrese cargas puntual sobre la que se desea el analisis de
fuerzas(coulomb):');
p=8.854*10^(-12);
k=1/(4*pi*p);
f=0;
fm=[];
for i=1:1:n
fprintf('carga numero: %d',i);
fprintf('\n');
q1=input('ingrese carga puntual(coulomb):');
r=input('ingrese la distancia(metros):');
f=f+k*q0*q1/r^2;
fm=[fm,f];
end
EJERCICIO 18
CHOQUES FRONTALES UNIDIMENSIONALES
cp1=m1*v01-m1*v01;
cp2=m2*v02-m1%Proceso para encontrar las velocidades de salida
p0=m1*v01+m2*v02;
v0e=v02-v01;
ek=e*v0e;
ds=-m1-m2;
dv1=-p0-m2*ek;
dv2=m1*ek-p0;
if ds==0
disp('No tiene solución');
else
v1=dv1/ds;
v2=dv2/ds;
end
%Proceso para encontrar la cantidad de movimiento lineal
% y las perdidas de energía
pf=m1*v1+m2*v2;
eco=0.5*m1*v01^2+0.5*m2*v02^2;
ec=0.5*m1*v1^2+0.5*m2*v2^2;
ep=(ec-eco)*100/eco;
%Variaciones 2*v02;
ce1=0.5*m1*(v1^2)-0.5*m1*(v01^2);
ce2=0.5*m2*(v2^2)-0.5*m2*(v02^2);
xa=d*abs(v01)/(abs(v01)+abs(v02));
ta=abs(xa/v01);
%Procedimiento para datos de x1 y x2 de recorrido
% Antes del choque
% Condiciones iniciales para el cuerpo 1 de entrada
da=xa/tramos;
dt1=ta/tramos;
punto1=1;
t(punto1)=0;
x1(punto1)=0;
x2(punto1)=d;
y1(punto1)=5;
y2(punto1)=5;
while (x1(punto1)<x2(punto1))
punto1=punto1+1;
t(punto1)=t(punto1-1)+dt1;
x1(punto1)=v01*t(punto1);
x2(punto1)=d-abs(v02*t(punto1));
y1(punto1)=5;
y2(punto1)=5;
end
%Procedimiento para sacar los datos de x3 y x4 de salida
%Condiciones iniciales para el cuerpo 1 de salida (después del choque)
t3=xa/v1;
dt3=dt1;
punto3=1;
x3(punto3)=xa;
x4(punto3)=xa;
y3(punto3)=5;
y4(punto3)=5;
tdc(punto3)=0;
while abs(x3(punto3)-xa)<(xa-da)
punto3=punto3+1;
tdc(punto3)=tdc(punto3-1)+dt3;
x3(punto3)=xa-abs(v1*tdc(punto3));
x4(punto3)=xa+v2*tdc(punto3);
y3(punto3)=5;
y4(punto3)=5;
end
%Salida
%Menú de opciones
op=1;
while op<3
disp('MENU DE OPCIONES')
disp('1. Mostrar Resultados numéricos');
disp('2. Gráficas de posiciones antes y después del choque');
disp('3. Simulación del movimiento de los cuerpos');
disp('4. Salir');
op=input('escoja una opción 1 o 2 -> : ');
switch op
case 1
%Proceso salida
disp('***** RESULTADOS: *****');
disp('La Velocidad de salida del:');
fprintf('- cuerpo 1 es v1(m/s) :%6.4f\n',v1);
fprintf('- cuerpo 2 es v2(m/s) :%6.4f\n',v2);
disp('La cantidad de movimiento:');
fprintf('- inicial en kg.m/s es:%6.4f\n',p0);
fprintf('- final en kg.m/s es:%6.4f\n',pf);
disp('La Energia Cinética: ');
fprintf('- inicial en Joule es:%6.4f\n', eco);
fprintf('- final en Joule es:%6.4f\n', ec);
disp('La VARIACION de:');
fprintf('- energía perdida en J es:%6.4f\n', ep);
fprintf('- momento lineal del cuerpo 1 en Kg.m/s es:%6.4f\n',cp1);
fprintf('- momento lineal del cuerpo 2 en Kg.m/s es:%6.4f\n',cp2);
fprintf('- energía del cuerpo 1 en J es:%6.6f\n',ce1);
fprintf('- energía del cuerpo 2 en J es:%6.6f\n',ce2);
disp(' Recorridos de los cuerpos: ');
fprintf('- El cuerpo 1 recorre xa(m)= %6.4f en un tiempo ta(s)= %6.4f
\n',xa,ta);
fprintf('- El cuerpo 2 recorre xb(m)= %6.4f en un tiempo tb(s)= %6.4f \n',d-
xa,ta);
% Graficas
subplot(3,2,1);
plot(t,x1);
title('Posición cuerpo 1 vs tiempo x1=v01t');
ylabel('Posición x1 (m)');
grid on;
subplot(3,2,3);
plot(t,x2,'r');
title('Posición cuerpo 2 vs tiempo x2=v02t');
ylabel('Posición x2 (m)');
grid on;
subplot(3,2,5);
plot(t,x1,t,x2,'r');
title('Posición del cuerpo 1 y 2 vs tiempo');
xlabel('tiempo t(s)');
ylabel('Posición x1 x2 (m)');
grid on;
subplot(3,2,4);
plot(tdc,x4,'r');
title('Posición cuerpo 2 vs tiempo x4=v2t');
ylabel('Posición x4 (m)');
grid on;
subplot(3,2,2);
plot(tdc,x3);
title('Posición cuerpo 1 vs tiempo x3=v1t');
ylabel('Posición x3 (m)');
grid on;
subplot(3,2,6);
plot(tdc,x3,tdc,x4,'r');
title('Posición del cuerpo 1 y 2 vs tiempo');
xlabel('tiempo t(s)');
ylabel('Posición x3 x4 (m)');
grid on;
case 3
% Animación
plot(x1,y1,x2,y2,x3,y3,x4,y4);
axis([0 (1.3*d) 0 (2*max(y1))]);
xlabel('x');
ylabel('y');
hold on;
%salida animación cuerpo 1 y 2
n=length(x1);
z=length(x3);
%Antes del choque
punto1=1;
while punto1<=n
plot(x1(punto1),y1(punto1),'ro','LineWidth',18);
axis([0 max(x4) 0 (2*max(y1))]);
hold on;
plot(x2(punto1),y2(punto1),'go','LineWidth',12);
Foto2(punto1)=getframe;
hold off;
punto1=punto1+1;
end
punto3=1;
while punto3<=z
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
rescate=0;
%%--- Outputs from this function are returned to the command line.
function varargout = Distanciaa_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
val=get(handles.Control, 'Value');
set(handles.valor,'string',fix(val));
hold on
% GRAFICAR
for i=1:1:300
n=get(handles.Control, 'Value');
% EL VALOR DE LA BARRA VERTICAL
hold on
axis([min(x) max(x) min(y) max(y)])
% GRAFICA EN GUIDE
plot(i,n,'*');
pause(1)
set(handles.Tiempo,'string',i);
% MUESTRA EL TIEMPO REAL
end
hold off
pos_01=uicontrol(gcf,'Style','edit','BackgroundColor','white','FontSize',10,'FontNam
e','Arial','String',[],'Position',[40 350 50
22],'CallBack','m_01=str2double(get(pos_01,''String''))');
pos_02=uicontrol(gcf,'Style','edit','BackgroundColor','white','FontSize',10,'FontNam
e','Arial','String',[],'Position',[40 325 50
22],'CallBack','m_02=str2double(get(pos_02,''String''))');
pos_03=uicontrol(gcf,'Style','edit','BackgroundColor','white','FontSize',10,'FontNam
e','Arial','String',[],'Position',[40 300 50
22],'CallBack','m_03=str2double(get(pos_03,''String''))');
pos_04=uicontrol(gcf,'Style','edit','BackgroundColor','white','FontSize',10,'FontNam
e','Arial','String',[],'Position',[100 350 50
22],'CallBack','m_04=str2double(get(pos_04,''String''))');
pos_05=uicontrol(gcf,'Style','edit','BackgroundColor','white','FontSize',10,'FontNam
e','Arial','String',[],'Position',[100 325 50
22],'CallBack','m_05=str2double(get(pos_05,''String''))');
pos_06=uicontrol(gcf,'Style','edit','BackgroundColor','white','FontSize',10,'FontNam
e','Arial','String',[],'Position',[100 300 50
22],'CallBack','m_06=str2double(get(pos_06,''String''))');
pos_07=uicontrol(gcf,'Style','edit','BackgroundColor','white','FontSize',10,'FontNam
e','Arial','String',[],'Position',[160 350 50
22],'CallBack','m_07=str2double(get(pos_07,''String''))');
pos_08=uicontrol(gcf,'Style','edit','BackgroundColor','white','FontSize',10,'FontNam
e','Arial','String',[],'Position',[160 325 50
22],'CallBack','m_08=str2double(get(pos_08,''String''))');
pos_09=uicontrol(gcf,'Style','edit','BackgroundColor','white','FontSize',10,'FontNam
e','Arial','String',[],'Position',[160 300 50
22],'CallBack','m_09=str2double(get(pos_09,''String''))');
npos_01=uicontrol(gcf,'Style','edit','BackgroundColor','white','FontSize',10,'FontNa
me','Arial','String',[],'Position',[220 350 50
22],'CallBack','n_01=str2double(get(npos_01,''String''))');
npos_02=uicontrol(gcf,'Style','edit','BackgroundColor','white','FontSize',10,'FontNa
me','Arial','String',[],'Position',[220 325 50
22],'CallBack','n_02=str2double(get(npos_02,''String''))');
npos_03=uicontrol(gcf,'Style','edit','BackgroundColor','white','FontSize',10,'FontNa
me','Arial','String',[],'Position',[220 300 50
22],'CallBack','n_03=str2double(get(npos_03,''String''))');
boton_calculo=uicontrol(gcf,'Style','push','FontSize',10,'FontName','Arial','String','C
alcular','Position',[50 250 150 22],'CallBack','fichero_01');
EJERCICIO 21
GRAFICA DE FUNCIONES
%38LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL
[x,y,z,v] = flow;
xmin = min(x(:));
ymin = min(y(:));
zmin = min(z(:));
xmax = max(x(:));
ymax = max(y(:));
zmax = max(z(:));
hslice = surf(linspace(xmin,xmax,100),...
linspace(ymin,ymax,100),...
zeros(100));
rotate(hslice,[-1,0,0],-45)
xd = get(hslice,'XData');
yd = get(hslice,'YData');
zd = get(hslice,'ZData');
delete(hslice)
figure
colormap(jet)
h = slice(x,y,z,v,xd,yd,zd);
h.FaceColor = 'interp';
h.EdgeColor = 'none';
h.DiffuseStrength = 0.8;
hold on
hx = slice(x,y,z,v,xmax,[],[]);
hx.FaceColor = 'interp';
hx.EdgeColor = 'none';
hy = slice(x,y,z,v,[],ymax,[]);
hy.FaceColor = 'interp';
hy.EdgeColor = 'none';
hz = slice(x,y,z,v,[],[],zmin);
hz.FaceColor = 'interp';
hz.EdgeColor = 'none';
daspect([1,1,1])
axis tight
view(-38.5,16)
camzoom(1.4)
camproj perspective
lightangle(-45,45)
colormap (jet(24))
EJERCICIO 24
%19pelota
figure
k = 5;
n = 2^k-1;
theta = pi*(-n:2:n)/n;
phi = (pi/2)*(-n:2:n)'/n;
X = cos(phi)*cos(theta);
Y = cos(phi)*sin(theta);
Z = sin(phi)*ones(size(theta));
colormap([0 0 0;1 1 1])
C = hadamard(2^k);
surf(X,Y,Z,C)
axis square
EJERCICIO 25
%37LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL
data = rand(12,12,12);
data = smooth3(data,'box',5);
isoval = .5;
h = patch(isosurface(data,isoval),...
'FaceColor','blue',...
'EdgeColor','none',...
'AmbientStrength',.2,...
'SpecularStrength',.7,...
'DiffuseStrength',.4);
isonormals(data,h)
patch(isocaps(data,isoval),...
'FaceColor','interp',...
'EdgeColor','none')
colormap hsv
daspect([1,1,1])
axis tight
view(3)
camlight right
camlight left
EJERCICIO 26
%36LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL
load wind
xmin = min(x(:));
xmax = max(x(:));
ymax = max(y(:));
zmin = min(z(:));
wind_speed = sqrt(u.^2 + v.^2 + w.^2);
hsurfaces = slice(x,y,z,wind_speed,[xmin,100,xmax],ymax,zmin);
set(hsurfaces,'FaceColor','interp','EdgeColor','none')
colormap jet
hcont = ...
contourslice(x,y,z,wind_speed,[xmin,100,xmax],ymax,zmin);
set(hcont,'EdgeColor',[0.7 0.7 0.7],'LineWidth',0.5)
[sx,sy,sz] = meshgrid(80,20:10:50,0:5:15);
hlines = streamline(x,y,z,u,v,w,sx,sy,sz);
set(hlines,'LineWidth',2,'Color','r')
view(3)
daspect([2,2,1])
axis tight
EJ
ER
CI
CIO 27
%35LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL
load wind
lims = [100.64 116.67 17.25 28.75 -0.02 6.86];
[x,y,z,u,v,w] = subvolume(x,y,z,u,v,w,lims);
cav = curl(x,y,z,u,v,w);
wind_speed = sqrt(u.^2 + v.^2 + w.^2);
[sx sy sz] = meshgrid(110,20:5:30,1:5);
verts = stream3(x,y,z,u,v,w,sx,sy,sz,.5);
h = streamribbon(verts,x,y,z,cav,wind_speed,2);
set(h,'FaceColor','r',...
'EdgeColor',[.7 .7 .7],...
'AmbientStrength',.6)
axis(volumebounds(x,y,z,wind_speed))
grid on
view(3)
camlight right;
EJERCICIO 28
%34LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL
load wind
xmin = min(x(:));
xmax = max(x(:));
ymin = min(y(:));
alt = 7.356; % z value for slice and streamtube plane
wind_speed = sqrt(u.^2 + v.^2 + w.^2);
hslice = slice(x,y,z,wind_speed,xmax,ymin,alt);
set(hslice,'FaceColor','interp','EdgeColor','none')
colormap hsv(16)
color_lim = caxis;
cont_intervals = linspace(color_lim(1),color_lim(2),17);
hcont = contourslice(x,y,z,wind_speed,xmax,ymin,...
alt,cont_intervals,'linear');
set(hcont,'EdgeColor',[.4 .4 .4],'LineWidth',1)
[sx,sy,sz] = meshgrid(xmin,20:3:50,alt);
daspect([1,1,1]) % set DAR before calling streamtube
htubes = streamtube(x,y,z,u,v,w,sx,sy,sz,[1.25 30]);
set(htubes,'EdgeColor','none','FaceColor','r',...
'AmbientStrength',.5)
view(-100,30)
axis(volumebounds(x,y,z,wind_speed))
set(gca,'Projection','perspective')
camlight left
EJERCICIO 29
%33LLLLLLLLLLLLLLLLLLLLLLLLLLLLL
load wind
[sx sy sz] = meshgrid(100,20:2:50,5);
verts = stream3(x,y,z,u,v,w,sx,sy,sz);
sl = streamline(verts);
view(-10.5,18)
daspect([2 2 0.125])
axis tight;
set(gca,'BoxStyle','full','Box','on')
iverts = interpstreamspeed(x,y,z,u,v,w,verts,0.01);
set(gca,'SortMethod','childorder');
streamparticles(iverts,15,...
'Animate',10,...
'ParticleAlignment','on',...
'MarkerEdgeColor','none',...
'MarkerFaceColor','red',...
'Marker','o');
EJERCICIO 30
%32PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP
load wind
wind_speed = sqrt(u.^2 + v.^2 + w.^2);
hiso = patch(isosurface(x,y,z,wind_speed,40));
isonormals(x,y,z,wind_speed,hiso)
hiso.FaceColor = 'red';
hiso.EdgeColor = 'none';
hcap = patch(isocaps(x,y,z,wind_speed,40),...
'FaceColor','interp',...
'EdgeColor','none');
colormap hsv
daspect([1 1 1]);
[f,verts] = reducepatch(isosurface(x,y,z,wind_speed,30),0.07);
h1 = coneplot(x,y,z,u,v,w,verts(:,1),verts(:,2),verts(:,3),3);
h1.FaceColor = 'blue';
h1.EdgeColor = 'none';
xrange = linspace(min(x(:)),max(x(:)),10);
yrange = linspace(min(y(:)),max(y(:)),10);
zrange = 3:4:15;
[cx,cy,cz] = meshgrid(xrange,yrange,zrange);
h2 = coneplot(x,y,z,u,v,w,cx,cy,cz,2);
h2.FaceColor = 'green';
h2.EdgeColor = 'none';
axis tight
camlight(-45,45)
hcap.AmbientStrength = 0.6;
lighting gouraud
set(gca,'BoxStyle','full','Box','on')
camproj perspective
camzoom(1.25)
view(65,45)
EJERCICIO 31
%21
vert = [0 0 0;0 1 0;1 1 0;1 0 0;0 0 1;0 1 1;1 1 4;1 0 4];
fac = [1 2 3 4;2 6 7 3;4 3 7 8;1 5 8 4;1 2 6 5;5 6 7 8];
patch('Vertices',vert,'Faces',fac,...
'FaceColor',[0.7 0.7 0.7],'EdgeColor','k')
view(3)
EJERCICIO 32
%DOS FIGURAS14
Mes = 1:12
T_Gr = [-2 0 2 4 8 12 14 14 12 8 4 0];
T_Ma = [-4 -2 0 2 6 14 18 18 16 8 2 -2];
subplot(2,1,1);
plot(Mes, T_Gr, 'bo-');
xlabel('Mes');
ylabel('Temperatura (°C)');
title('Temperaturas minimas en Granada');
grid;
subplot(2,1,2);
plot(Mes, T_Ma, 'rv-');
xlabel('Mes');
ylabel('Temperatura (°C)');
title('Temperaturas minimas en Madrid');
grid;
EJERCICIO 33
%13
Mes = 1:12;
T_Gr = [-2 0 2 4 8 12 14 14 12 8 4 0];
T_Ma = [-4 -2 0 2 6 14 18 18 16 8 2 -2];
plot(Mes, T_Gr, 'bo', Mes, T_Ma, 'rv');
xlabel('Mes');
ylabel('Temperatura (°C)');
title('Temperaturas minimas en Granada y Madrid');
legend('Granada','Madrid');
grid;
EJERCICIO 34
%12
load fisheriris;
X= meas(1:100,:);
Group= species(1:100);
[IDX, Z] = rankfeatures(X',Group);
% Selecionamoslas variables más discriminativas
data= X(:,[IDX(1) IDX(2)]);
% Selección aleatoria de subconjuntos de entrenamiento y test
[train, test] = crossvalind('holdOut',Group);
cp= classperf(Group);
% Entrenamiento de una máquina de vectores de soporte
svmStruct= svmtrain(data(train,:),Group(train),'showplot',true);
% Añadimos título.
title(sprintf('KernelFunction: %s',...
func2str(svmStruct.KernelFunction)),...
'interpreter','none');
% Clasificación del conjunto de test
classes= svmclassify(svmStruct,data(test,:),'showplot',true);
% Evaluación a partir de la tasa de correctas.
classperf(cp,classes,test);
cp.CorrectRate
EJERCICIO 35
%Análisis discriminante10:
load fisheriris
SL = meas(51:end,1);
SW = meas(51:end,2);
group = species(51:end);
h1 = gscatter(SL,SW,group,'rb','v^',[],'off');
set(h1,'LineWidth',2)
legend('Fisher versicolor','Fisher virginica','Location','NW')
EJERCICIO 36
t = linspace(-pi, pi);
x = 12.*sin(t) -4.*sin(3.*t) ;
y = 13.*cos(t) - 5.*cos(2.*t) - 2.*cos(3.*t) - cos(4.*t);
area(x,y)
set(findobj('Type','patch'),'lineStyle','none','FaceColor',[.34 .8 .59]);%cambiar de
color
EJERCICIO 44
%corazon polar24
t = 0:.01:2*pi;
f = ( cos(t) .* sqrt(abs(sin(t))) ) ./ (cos(t) + 7/5) - 2 .* cos(t) + 2;
polar(t,f)
set(findobj('Type','line'),'Color',[.31 .4 .58],'Linewidth', 2);
EJERCICIO 45
%corazon polar24
%3D DOS FIGURAS23
x=[-2.1:0.15:2.1];
y=[-6:0.15:6];
[X,Y]=meshgrid(x,y);
Z= 80*Y.^2.*exp(-X.^2 - 0.3*Y.^2);
mesh(X,Y,Z)
EJERCICIO 46
%FUNCION22
t = linspace(0, 2*pi, 200);
a = 10; b = 1.0; c = 0.3;
x = b*cos(t);
y = b*sin(t);
z = c*cos(a*t);
plot3(x, y, z, 'k')
axis equal
EJERCICIO 47
%3D18
[x,y]=meshgrid(-3: 0.2 :3);
z=sin(x)+ cos(y);
ribbon(y ,z, 0.8);
xlabel('x')
ylabel('y')
zlabel('z')
EJERCICIO 48
%3D16
a=-2.1:0.3:2.1;
b=-2.1:0.4:2.1;
[x,y]=meshgrid(a,b);
z=sqrt(9-x.^2-y.^2);
[u,v,w]=surfnorm(x,y,z);
quiver3(x,y,z,u,v,w,0.8)
hold on
EJERCICIO 49
%CILINDRO15
t = 0:pi/50:10*pi;
plot3(sin(t),cos(t),t, 'r');
EJERCICIO 50
% 2 FIGURAS DE 3D14
x = -2:0.1:2;
y = -2:0.1:2;
[X,Y] = meshgrid(x,y);
Z = X.*exp(-X.^2 - Y.^2);
subplot(1,2,1);
mesh(X,Y,Z);
subplot(1,2,2);
contour(X,Y,Z);
EJERCICIO 51
%3D13
[x,y]=meshgrid(-1.5:0.2:1.5);
z=sin(x.^2+y.^2);
surf(x,y,z);
xlabel('x');
ylabel('y');
zlabel('z');
plot3(x,y,z)
c=[1 0.8 0.1];
fill3(x,y,z,c)
EJERCICIO 52
%3D12
[x,y]=meshgrid(-1.5:0.2:1.5);
z=x.^2+y.^2-9;
surf(x,y,z);
xlabel('x');
ylabel('y');
zlabel('z');
EJERCICIO 53
%3D11
[x,y]=meshgrid(-1.5:0.2:1.5);
z=x.^2+y.^2-9;
meshz(x,y,z);
xlabel('x');
ylabel('y');
zlabel('z');
EJERCICIO 54
%funcion1
x=-1:0.1:5;
y=sin(x.^2);
plot(x,y)
EJERCICIO 55
%BARRAS2
x=-3:0.2:3;
y=exp(-x.^2);
plot(x,y)
Bar(x,y)
EJERCICIO 56
x1= [-12 -5 0 -5 -12 -5 0 -1 2 -1 0 -1 2 -1 0 2 5 2 0 2 5];
x12= [-11 -4 0 -4 -11 -4 0 1 -2 1 0 1 -2 1 0 2 5 2 0 2 5];
y1= [-3 -5 0 5 3 5 0 -3 -7 -3 0 3 7 3 0 -3 -2 -3 0 3 2];
z1= [-1 1 -1 1 -1 1 -1 1 -1 1 -1 1 -1 1 -1 1 -1 1 -1 1 -1];
hhh=pi/10;
u= 0:hhh:2*pi;
v= 0:hhh:pi;
nv= length(v);
nu= length(u);
ya= sin(v);
ya=ya';
za= cos(v');
zb=za;
for i= 2:nu
za= [za zb]; %#ok<AGROW>
end
t1= 5*ya*cos(u)-5;
t2= 4*ya*sin(u);
t2z= za;
mesh(t1,t2,t2z)
t3=2*ya*cos(u)+2;
t4=2*ya*sin(u);
t4z=za;
hold on
mesh(t3,t4,t4z)
plot3(x1,y1,z1,'linewidth',3)
view( [130.7 7.3])
axis( [-12 12 -8 8 -1 8])
grid on
EJERCICIO 57
hr=pi/30;
t=0:hr:2*pi;
x0=cos(t); y0=0*t; z0=sin(t);
x1=(x0-2); y1=(y0-1); z1=z0;
x2=(0.6*x0+2); y2=(y0-1); z2=(0.6*z0);
x3=(x0-2); y3=(y0+1); z3=z0;
x4=(0.6*x0+2); y4=(y0+1); z4=0.6*z0;
x5=0.3*x0-1; y5=y0; z5=(0.5*z0+3);
plot3(x1,y1,z1,'linewidth',3,'color','k')
axis([-5 5 -4 4 -2 6])
grid on
hold on
plot3(x2,y2,z2,'linewidth',3,'color','k')
plot3(x3,y3,z3,'linewidth',3,'color','k')
plot3(x4,y4,z4,'linewidth',3,'color','k')
y6=[-1 1 -0.5 -0.5 0.5 0.5 0.5 -0.5 -0.5 -0.5 -0.5 -0.5 0.5 0.5 -0.5 -0.5 0.5 0.5 0.5 0.5
0.5 0.5 0.5 -0.5 -0.5 -0.5 -0.5];
x6=[-2 -2 -2 -2 -2 -2 2 2 -2 -2 0.3 0 0 0.3 0.3 -2 -2 0 0.3 0 -2 -2 -2 -2 -2 0 -2];
z6=[0 0 0 1 1 0 0 0 0 1 1 0 0 1 1 1 1 1 1 1 1.5 1 1.5 1.5 1 1 1.5];
y7=[-1 1 -0.5 0 0.5 0 -0.5 -0.5 -0.5 0.5 0.5];
x7=[2 2 2 1 2 1 1 1 1 1 1];
z7=[0 0 0 1.5 0 1.5 1.5 1.7 1.5 1.5 1.7];
x8=[0 1 0 1 -1 -1 -1 0.5 1 0.5 0 0.5 1];
y8=[0.5 0 -0.5 0 0 0 0 0.5 0.5 0.5 0 -0.5 -0.5];
z8=[0 1 0 1 1 2.5 2 1 1.7 1 2 1 1.7];
x9=3*[-0.23 -0.2 0.2 0.23 -0.23 -0.1 -0.1 0.1 0.1]-1;
y9=3*[0 0 0 0 0 0 0 0 0];
z9=3*[1.05 0.9 0.9 1.05 1.05 1.15 1.15 1.05]+0.5;
plot3(x6,y6,z6,'linewidth',3,'color','m')
plot3(x7,y7,z7,'linewidth',3,'color','m')
plot3(x8,y8,z8,'linewidth',4,'color', [0 0 1] )
patch(x5,y5,z5,[1 0.5 0.5])
patch(x9,y9,z9,[0 1 1])
hold off
EJERCICIO 58
x=2:2:8;
y=[zeros(1,length(x)); cos(pi*x/20)];
plot([x;x],y,'k')
plot([x;x],y,'k',x,cos(pi*x/20),'rs')
axis([1,9,0,1])
EJERCICIO 59
EN MOVIMIENTO
n=300;s=0.02;
n_tr=50;
x=rand(n,1)-0.5;
y=rand(n,1)-0.5;
h=plot(x,y,'.')
set(h,'MarkerSize',18)
axis([-1 1 -1 1])
axis square
grid off
M=moviein(n_tr);
for k=1:n_tr
x=x+s*randn(n,1);
y=y+s*randn(n,1);
set(h,'xData',x,'yData',y)
M(:,k)=getframe;
end
movie(M,5)
EJERCICIO 60
DIAGRAMA DE BARRAS ESTADISTICOS
x = [10 2 3 4 18 20 15];
subplot(2,2,1), bar(x), title('Barras verticales')
subplot(2,2,2), barh(x), title('Barras horizontales')
subplot(2,2,3), bar3(x), title('Barras verticales 3D')
subplot(2,2,4), bar3h(x), title('Barras horizontales 3D')
EJERCICIO 61
%% Primer guión para remover datos atípicos
clc; clear; close all
%% Información de entrada
Y = [10 20 -150 40 50 60 70 200 90 100];
X = [2 4 6 8 10 12 14 16 18 20];
%% Cálculos
IQR = iqr(Y);
%intervalo intercuartil,
% la diferencia entre el tercer y el primer cuartil
% de una distribución: 75%-25% de Y
% ?= IQR * 0.7413
lowr=prctile(Y,25)-1.5*IQR;
%Percentiles. Q1 - 1.5IQR.
highr=prctile(Y,75)+1.5*IQR;
% Q3 + 1.5IQR
%%ver; es creer
hold on
plot(X, Y, 'bo','MarkerSize',20)
plot(new_X, new_Y, 'kx','MarkerSize',20)
hold off
%fin del guión
EJERCICIO 62
%%% Inicio código 1: Filtro convolución
clc
clear
close all
x = 0:0.0001:10;
r = ones(size(x));
for k= 1:length(x)
if x(k) <= 0.15
r(k)= .50;
elseif x(k) <= 0.30
r(k)= 0.25;
elseif x(k) <= 0.60
r(k)= 0.10;
else
r(k)= 0;
end
end
plot(x,r, 'LineWidth',3)
axis([-.2,3,-0.2,0.6])
Y= ifft( fft(y).*fft(r));
figure
hold on
plot(x, y/max(y), '--b','LineWidth',3)
plot(x,Y/max(Y), 'k', 'LineWidth',3)
axis([0,10,0.28,1.05])
hold off
%%% Fin código 1: Filtro convolución
EJERCICIO 63
% Superficie 3D con una textura de imagen
% Inicialización
clear all; close all; clc; format compact;
% Dibujando la superficie
h = surf(x,y,z);
defImage = pow2(get(0,'DefaultImageCData'),47);
imgCell = repmat({zeros(size(defImage))},8,7);
for shift = 0:52
imgCell{shift+1} = bitshift(defImage,shift);
end;
allImages = cell2mat(imgCell.');
imshow(allImages,[min(allImages(:)) max(allImages(:))]);
EJERCICIO 65
MOVIMIENTO CIRCULAR
clear
figure(1)
%variables
x=[];
v=[];
F=[];
%parametros
m=1;
M=1e20;
G=6.67e-11;
h=0.01;
%condiciones iniciales
x=[-1e3;0];
v=[0;-2e3];
%variable externa
F=-G*(m*M/norm(x)^2)*(x/norm(x));
for step=1:500
hold off;
scatter(x(1),x(2), 'black','filled');
hold on
scatter(0,0,'black','filled');
%paso integración
F=-G*(m*M/norm(xa)^2)*(xa/norm(xa));
vpm = va + (h/2)*(F/m);
xpm = xa + (h/2)*va;
F=-G*(m*M/norm(xpm)^2)*(xpm/norm(xpm));
v = va + h*(F/m);
x = xa + h*vpm;
end
EJERCICIO 66
% Inicio del código
%% ejemplo del uso de las funciones FFT y MAX para limpiar una señal
%% con ruido
%% 12 sept 2011
% limpieza de la memoria
clc
clear
close all
axis([-2,2,-2,2,- 2,2])
EJERCICIO 68
TIRO PARABOLICO
clear
figure(1)
%variables
x=[];
v=[];
F=[];
%parametros
m=1;
g=[0;-9.81];
h=0.01;
%condiciones iniciales
x=[0;0];
v=[0.1;4];
%variable externa
F=m*g;
for step=1:100
plot(x(1),x(2),'ob');
%paso integración
vpm = va + (h/2)*(F/m);
xpm = xa + (h/2)*va;
v = va + h*(F/m);
x = xa + h*vpm;
end
EJERCICIO 69
clear
figure(1)
theta_graf=[];
%variables
theta=[];
w=[];
%parametros
m = 1;
g = 9.81;
L = 1; %longitud del péndulo
C = 0.75; %constante de fricción viscosa
h=0.01;
%condiciones iniciales
theta = 30*(pi/180); %entre –pi/2 y pi/2 en radianes
x=[L*sin(theta);-L*cos(theta)];
w = 0/L;
%entrada
alpha = -(L*w*C + m*g*sin(theta))/(L*m);
for step=1:1000
hold off
plot(x(1),x(2),'o', 'MarkerFaceColor','b','MarkerSize',10);
hold on
plot([0;x(1)],[0;x(2)]);
theta_a = theta;
wa = w;
%paso integración
wpm = wa + (h/2)*alpha;
theta_pm = theta_a + (h/2)*wa;
alpha_pm = -(L*wpm*C + m*g*sin(theta_pm))/(L*m);
w = wa + h*alpha_pm;
theta = theta_a + h*wpm;
x=[L*sin(theta);-L*cos(theta)];
alpha = -(L*w*C + m*g*sin(theta))/(L*m);
end
EJERCICIO 70
% Formación de ondas en el agua.
clear all
clc
for freq=0.1:0.1:2*pi
% Ecuación de la onda:
Z=sin((2*pi-freq)*k*R+phi);
surf(X,Y,Z,'Facecolor','blue','Edgecolor','none');
% Usamos Facecolor para seleccionar el color de nuestra
% onda, en nuestro caso azul. Y usamos Edgecolor para
% el color de la retícula de la onda, en nuestro caso
% usamos none para que no haya.
axis equal;
% Mediante este comando logramos igualar los tamaños
% de los ejes.
%Inputs
% Radio de la Onda
r=(X.^2+Y.^2).^0.5;
% Programa:
for t = 0:0.1:Tiempo
% Mediante estos dos bucles y el condicional distinguimos los dos casos
% de la distancia al foco para determinar la Amplitud de la onda.
for i = 1:n
for j = 1:n
if (r(i,j))>r0
A = 1./(r(i,j).^0.5);
% Ecuación de la onda:
Z(i,j) = A.*(sin(2*pi.*((r(i,j)./long)-(t/T))));
else
Z(i,j) = sin(2*pi.*((r(i,j)./long)-(t/T)));
end
end
end
surf(X,Y,Z,'Facecolor','blue','Edgecolor','none');
M(count)=getframe;
count=count+1;
end
EJERCICIO 72
%Rutina para simular la trayectoria de una partícula browniana
% Por Vicente Torres Zúñiga
clear % limpiamos memoria
close all
clc
par=1; % número de particulas,
%soporta hasta 21 particulas para diferenciar el color
% espacio para los valores finales de posicion de las partículas
X=zeros(par,1000);
Y=zeros(par,1000);
Z=zeros(par,1000);
for n=1:par %número de particulas en cada interación
x=zeros(1,1000); %vector de posicion de la particula
y=zeros(1,1000);
z=zeros(1,1000);
%se define una dirección en 3D aleatoria.
phi=2*pi*rand(1,1000);%crea un ángulo aleatorio para la particula
theta=2*pi*rand(1,1000)-pi; %se crea el otro ángulo.
% bastan con dos angulos para cubrir el espacio
for i=1:999 %se define la interacción de la partícula
x(i+1)=x(i)+cos(phi(i)).*sin(theta(i));
y(i+1)=y(i)+sin(phi(i)).*sin(theta(i));
z(i+1)=z(i)+cos(theta(i));
end
%se guarda la trayectoria instantanea de cada partícul
X(n,:)=x;
Y(n,:)=y;
Z(n,:)=z;
end
% vector para cambiar de color en cada trayectoria
C=['r' 'g' 'b' 'w' 'y' 'm' 'c' 'r' 'g' 'b' 'w' 'y' 'm' 'c' 'r' 'g' 'b' 'w' 'y' 'm' 'c'];
%graficación de la trayectoria de las partículas
hold on
for n=1:par;
plot3(X(n,:),Y(n,:),Z(n,:),C(n));
% en lugar de graficar las trayectorias de cada particula,
% se grafica en esa posición el lugar que ocupa la partícula
end
view(3);
axis tight % Ajustes en la visualización de la ventana
box on
hold off
EJERCICIO 73
%%%% inicia código
x=0:.01:7; y=plot(x,sin(x));
hCursorbar = graphics.cursorbar(y); drawnow
hCursorbar.CursorLineColor = [1,.2,.3]; % default=[0,0,0]='k'
hCursorbar.CursorLineStyle = ':'; % default='-'
hCursorbar.CursorLineWidth = 1; % default=1
hCursorbar.Orientation = 'vertical'; % =default
hCursorbar.TargetMarkerSize = 10; % default=8
hCursorbar.TargetMarkerStyle = 'o'; % default='s' (square)
%%%% fin del código
EJERCICIO 74
syms x
syms y
ezsurf(cos(y^2)*exp(-sqrt(y^2+x^2)))
o si la funcion es:
syms y
syms x
ezsurf(cos(y^2)^(-sqrt(y^2+x^2)))
EJERCICIO 75
clc;
fprintf('METODO DE LA FALSA POSICION \n');
a=input('Ingrese el intervalo inferior: ');
c=input('Ingrese el intervalo superior: ');
e=input('Ingrese el error: ');
Fx=input('Ingrese la funcion: ','s');
x=a;
Fa=eval(Fx);
x=c;
Fc=eval(Fx);
if Fc*Fa<0
fprintf('\n %6s %7s %8s %10s %8s %8s %8s %8s %8s \n
','A','B','C','F(a)','F(b)','F(c)','|c-a|','|a-b|','|c-b|');
Fb=100;
while(abs(Fb)>e)
b=(c*Fa-a*Fc)/(Fa-Fc);
x=b;
Fb=eval(Fx);
fprintf('\n %8.4f %8.4f %8.4f %8.4f %8.4f %8.4f %8.4f %8.4f %8.4f
\n',a,b,c,Fa,Fb,Fc,abs(c-a),abs(a-b),abs(c-b));
if Fa*Fb<=0
c=b;
Fc=Fb;
else
a=b;
Fa=Fb;
end
end
fprintf('\nEl resultado sera %.4f\n',b);
ezplot(Fx);%graficamos la funcion
grid on;
else
fprintf('no existe raíz en este intervalo');
end
EJERCICIO 76
clc;
fprintf('METODO DE LA BISECCIÓN \n');
a=input('Ingrese el intervalo inferior: ');
c=input('Ingrese el intervalo superior: ');
e=input('Ingrese el error: ');
Fx=input('Ingrese la funcion: ','s');
x=a;
Fa=eval(Fx);
x=c;
Fc=eval(Fx);
if Fc*Fa<0
fprintf('\n %6s %7s %8s %10s %8s %8s %8s %8s %8s \n
','A','B','C','F(a)','F(b)','F(c)','|c-a|','|a-b|','|c-b|');
Fb=100;
while(abs(Fb)>e)
b=(a+c)/2;
x=b;
Fb=eval(Fx);
fprintf('\n %8.4f %8.4f %8.4f %8.4f %8.4f %8.4f %8.4f %8.4f %8.4f
\n',a,b,c,Fa,Fb,Fc,abs(c-a),abs(a-b),abs(c-b));
if Fa*Fb<=0
c=b;
Fc=Fb;
else
a=b;
Fa=Fb;
end
end
fprintf('\nEl resultado sera %.4f\n',b);
ezplot(Fx);%graficamos la funcion
grid on;
else
fprintf('no existe raíz en este intervalo');
end
EJERCICIO 77
SIMPSOM
function simpson13;
f=input(' ingrese la funcion a integrar f(x)= ','s');
a=input(' ingrese el limite inferior: ');
b=input(' ingrese el limite superior: ');
fprintf(' ingrese el numero de trapecios a \n ');
n=input(' considerar en la integracion : ');
n=2*n;
xmin=a-1;xmax=b+1;
h=(b-a)/n;
x=a:h:b;
fx=eval(f);y=abs(fx);
suma1=y(1)+y(n+1);
suma2=4*sum(y(2:2:n));
suma3=2*sum(y(3:2:n-1));
suma=suma1+suma2+suma3;
integral=(h/3)*suma;
fprintf('el area es :%10.9f\n',integral);
%grafica
xp=xmin:0.2:xmax;
x=xp;
yp=eval(f);
plot(xp,yp,'g');
hold on
x=a:0.05:b;
y=eval(f);
bar(x,y,'r');
grid;
EJERCICIO 78
clear x
p=0.5;
deltax=1;
T=10000;
x(1)=0;
for i=2:T
if (rand < p)
x(i)=x(i-1)+deltax;
else
x(i)=x(i-1)-deltax;
end
end
plot(1:T,x)
grid on
xlabel('n');
ylabel('x_n');
EJERCICIO 79
clear x
p=0.5;
deltax=1;
T=1000;
for part=1:100
x(1,part)=0;
for i=2:T
if (rand < p)
x(i,part)=x(i-1,part)+deltax;
else
x(i,part)=x(i-1,part)-deltax;
end
end
end
plot(1:T,x)
xlabel('tiempo');
ylabel('posición');
EJERCICIO 80
m=10;M=100; %datos de masa de particula y totales
x=zeros(1,10);
y=zeros(1,10);
z=zeros(1,10);
for i=1:10
x(i)=m*(i-1)/5;
y(i)=m*sin(pi*(i-1)/4);
z(i)=m*pi*(i-1)/30;
end
xg=0;
yg=0;
zg=0;
for i=1:10 %bucle que a los puntos con la masa ya asignada suma todas las
componentes posibles del mismo para dividir entre masa total
xg=x(i)+xg;
yg=y(i)+yg;
zg=z(i)+zg;
end
Xg=xg/M;
Yg=yg/M;
Zg=zg/M;
G=[Xg Yg Zg];%coordenadas del centro de masas
sprintf('El centro de masas es: %f %f %f',G)
plot3(Xg,Yg,Zg,'*g') %comando de visualización del mismo
EJERCICIO 81
x=zeros(1,10);% Matrices de ceros para inscribir en ellas
y=zeros(1,10);
z=zeros(1,10);
for i=1:10 %Bucle para obtener las coordenadas de los puntos
x(i)=(i-1)/5;
y(i)=sin(pi*(i-1)/4);
z(i)=pi*(i-1)/30;
end
th=pi/12; %Ángulo de giro decidido para experimentar dicha rotación
eje=[0,0,1];
A=cos(th)*eye(3); %Matrices de la rotación
B=(1-cos(th))*(eje'*eje);
C=sin(th)*[0 -eje(3) eje(2);eje(3) 0 -eje(1);-eje(2) eje(1) 0];
R1=A+B+C;
pos=[x',y',z']; % Ensamblaje de las coordenadas de todos los puntos en una matriz
vel=pos*R1; %Con el producto de las coordenadas con la rotación obtenemos los
puntos finales de cada una de las coordenadas de los puntos.
vfx=vel(:,1)';
vfy=vel(:,2)';
vfz=vel(:,3)';
tre=vel-pos;
hold on %mantenemos el gráfico para obtener el grafico de las posiciones iniciales
y el de los vectores que unen la posición final con la inicial
plot3(x,y,z,'-*')
quiver3(x,y,z,vfx,vfy,vfz,'r--')
axis([-2,2,-2,2,-2,2])
hold off
EJERCICIO 82
m=10;
p=[0.9 0.070711 0.471239];%Punto en el que queremos hallar el momento de
inercia
Mg=[0.9 0.070711 0.471239]; % Coordenadas del centro de masas
a=Mg-p;
B=m*(((a*a')*eye(3))-a'*a); %Matriz del elemento que toma como 'a' el vector que
une P con MG
x=zeros(1,10);
y=zeros(1,10);
z=zeros(1,10);
for i=1:10 %Bucle para obtener las coordenadas
x(i)=(i-1)/5;
y(i)=sin(pi*(i-1)/4);
z(i)=pi*(i-1)/30;
end
pos=[x' y' z'];
Ig=zeros(3,3);
for i=1:10
Ig=m*(pos(i,:))*(pos(i,:)')*eye(3)-m*(pos(i,:)')*(pos(i,:))+Ig;
%Que viene de la definición anterior
end
Ip=Ig+B
EJERCICIO 83
SEÑAL DISCRETA
clc
clear
pause on
x=[0 1 2 3 4 3 2 1 0]; %Respuesta al impulso unitario
h=[1 1 1 1 1 1 1 1 ]; %Señal de entrada
m=length(x);
n=length(h);
%invierte el vector h
hi=fliplr(h);
k=20;
X=[x,zeros(1,40-m)];
X= X([ end-k+1:end 1:end-k ]);
H=[h,zeros(1,40-n)];
H= H([ end-k+1:end 1:end-k ]);
xn=-20:20-1;
Y=zeros(1,40);
p=zeros(1,40);
h1=subplot(3,1,1);
stem(xn,X,'MarkerFaceColor','red')
ylabel('h[n]')
title('Respuesta al impulso unitario')
% set(h1,'YLim',[a b])
h2=subplot(3,1,2);
stem(xn,H,'MarkerFaceColor','blue')
% set(h2,'YLim',[a b])
pause(3)
h2=subplot(3,1,3);
stem(xn,Y,'MarkerFaceColor','green')
%
Hi=[hi,zeros(1,40-n)];
for i=1:40-n
p=X.*Hi;
Y(i+n-1)=sum(p);
subplot(3,1,2);
stem(xn,Hi,'MarkerFaceColor','blue')
ylabel('x[n]')
title('Señal de entrada')
subplot(3,1,3)
stem(xn,Y,'r','MarkerFaceColor','green')
xlabel('Tiempo [n]')
ylabel('y[n]')
title('Señal de salida')
Hi= Hi([ end 1:end-1 ]);
pause(0.5)
end
pause off
salida=Y(abs(Y)>0);
salida2=conv(x,h);
[salida',salida2']
EJERCICIO 84
SEÑAL CONTINUA
clc
clear
pause on
x=[0 1 2 3 4 3 2 1 0]; %Respuesta al impulso unitario
h=[1 1 1 1 1 1 1 1 ]; %Señal de entrada
m=length(x);
n=length(h);
%invierte el vector h
hi=fliplr(h);
k=20;
X=[x,zeros(1,40-m)];
X= X([ end-k+1:end 1:end-k ]);
H=[h,zeros(1,40-n)];
H= H([ end-k+1:end 1:end-k ]);
xn=-20:20-1;
Y=zeros(1,40);
p=zeros(1,40);
h1=subplot(3,1,1);
plot(xn,X,'-g')
ylabel('h(t)')
title('Respuesta al impulso unitario')
% colocar(h1,'YLim',[a b])
h2=subplot(3,1,2);
plot(xn,H,'-y')
% colocar(h2,'YLim',[a b])
pause(3)
h2=subplot(3,1,3);
plot(xn,Y,'-m')
%ciclo
Hi=[hi,zeros(1,40-n)];
for i=1:40-n
p=X.*Hi;
Y(i+n-1)=sum(p);
subplot(3,1,2);
plot(xn,Hi,'-r')
ylabel('x(t)')
title('Señal de entrada')
subplot(3,1,3)
plot(xn,Y,'-m')
xlabel('Tiempo [s]')
ylabel('y(t)')
title('Señal de salida')
Hi= Hi([ end 1:end-1 ]);
pause(0.5)
end
pause off
salida=Y(abs(Y)>0);
salida2=conv(x,h);
[salida',salida2']
EJERCICIO 85
figure(1);
for i=1:1000
T(i)=cos(i);
plot(T);
drawnow;
pause(0.3)
end
EJERCICIO 86
t=linspace(0,0.7,100);
g=7; %amortiguamiento
w0=100; %frecuencia angular natural
fi=1.5; %fase
A=5.01; %amplitud
w=sqrt(w0*w0-g*g);
x=A*exp(-g*t).*sin(w*t+fi);
v=-g*A*exp(-g*t).*sin(w*t+fi)+w*A*exp(-g*t).*cos(w*t+fi);
e=(v.^2+w0*w0*x.^2)/2;
subplot(2,2,1)
plot(t,x)
grid on
xlabel('tiempo (s)')
ylabel('posición (m)')
subplot(2,2,2)
plot(t,e)
grid on
xlabel('tiempo (s)')
ylabel('energía (J)')
subplot(2,2,3)
plot(t,v)
grid on
xlabel('tiempo (s)')
ylabel('velocidad (m/s)')
subplot(2,2,4)
plot(x,v)
grid on
xlabel('posición (m)')
ylabel('velocidad (m/s)')
EJERCICIO 87
t=linspace(0,0.7,100);
x=5*exp(-7*t).*sin(100*t+1.5);
A=5*exp(-7*t);
hold on
plot(t,x,'r')
plot(t,A,'b')
plot(t,-A,'b')
hold off
legend('desplazamiento','amplitud')
title('Oscilaciones amortiguadas')
xlabel('t')
ylabel('x')
EJERCICIO 88
r0=0.4;
b=0.05;
ang=0:pi/18:9*pi/2;
r=r0*exp(b*ang);
polar(ang,r,'r')
title('Espiral logarítmica')
EJERCICIO 89
r=linspace(0,1,30);
angulo=linspace(0,2*pi,30);
[r,angulo]=meshgrid(r,angulo);
x=r.*cos(angulo);
y=r.*sin(angulo);
z=r;
mesh(x,y,z)
xlabel('x-axis'); ylabel('y-axis'); zlabel('z-axis')
EJERCICIO 90
MOVIMIENTO
% Animación
for i=1:length(x)
set(hg,'XData',x(i),'YData',0);
drawnow;
end
EJERCICIO 91
x=linspace(-1.5,4.5,50);
f=@(x) -x.^2+3*x+4;
y=f(x);
hold on
plot(x,y,'b')
line([-2 5],[0 0],'color','k'); %eje horizontal X
xx=[1 1 x(x>1 & x<3) 3 3];
yy=[0 f(1) y(x>1 & x<3) f(3) 0];
fill(xx,yy,'y'); %rellena un área de color especificado
title('área')
xlabel('X')
ylabel('Y')
hold off
EJERCICIO 93
clear
t=0:30:330;
x=[408 89 -66 10 338 807 1238 1511 1583 1462 1183 804];
hold on
plot(t,x,'ro','markersize',2,'markerfacecolor','r')
xlim([0 360])
xlabel('Ascensión (Grados)')
ylabel('Declinación (Minutos)')
title('Posición del asteroide Pallas')
grid on
n=length(x);
w=2*pi/360;
a0=sum(x)/n;
k=1:6;
a=cos(w*k'*t)*x'*2/n;
b=sin(w*k'*t)*x'*2/n;
t=0:360;
x=a0+a'*cos(w*k'*t)+b'*sin(w*k'*t);
plot(t,x,'b')
hold off
color=['b','r','g'];
EJERCICIO 94
D=20e-9;
x=linspace(-0.5,0.5,200);
t=[1,15,50]*3600; %horas a segundos
hold on
for i=1:length(t)
c=(1-erf(x/(2*sqrt(D*t(i)))))/2;
plot(x,c,color(i),'displayName',num2str(t(i)/3600))
end
hold off
legend('-DynamicLegend','location','Best')
xlabel('x')
ylabel('c/c_0')
title('Difusión de sal en agua')
grid on
EJERCICIO 95
n=5;
k=1:n;
ang=(2*k-1)*pi/(2*n);
xk=cos(ang);
yk=sin(ang);
hold on
plot(cosd(1:180),sind(1:180),'b')
for i=1:length(xk)
line([0,xk(i)],[0,yk(i)])
hg=line([xk(i),xk(i)],[0,yk(i)]);
set(hg,'linestyle','--');
end
line([-1,1],[0,0])
plot(xk,0,'ro','markersize',4,'markerfacecolor','r')
hold off
axis equal
title('Raíces')
EJERCICIO 96
k_m=sqrt(60);
A=0.15;
t=0:0.2:25;
[sn,cn,dn]=ellipj(A*k_m*t,1/2);
hold on
plot(t,cn*A,'b')
A=0.3;
[sn,cn,dn]=ellipj(A*k_m*t, 1/2);
plot(t,cn*A,'r')
hold off
xlabel('t')
ylabel('x')
legend ('0.15','0.3')
title('Desplazamiento en función del tiempo')
grid on
EJERCICIO 97
% x = t;
% y = v(t);
x = 0:45;
y = 0.2 + 3*x.^2;
hold on
grid
for i=1:length(x)-1
hold on
axis([min(x) max(x) min(y) max(y)])
plot(x(i:i+1),y(i:i+1),'linewidth',2);
pause(0.001)
end
hold off
EJERCICIO 98
x = round(20*rand(10,1))
y = round(20*rand(10,1))
nombres = cellstr(num2str([1:10]'));
axis([min(x) max(x) min(y) max(y)])
for i = 1:10
axis([min(x) max(x) min(y) max(y)])
plot(x(i),y(i),'rx')
text(x(i),y(i), nombres{i},'VerticalAlignment','bottom','HorizontalAlignment','Right')
pause(0.5)
hold on
end
hold off
EJERCICIO 99
x=[0.97 1.12 2.92 3.00 3.33 3.97 6.10 8.39 8.56 9.44];
y=[2.58 0.43 0.06 5.74 7.44 8.07 6.37 2.51 1.44 0.52];
xx=[1.0 2.0 3.5 5.5 8.0];
yy=interp1(x,y,xx,'linear');
disp([xx' yy'])
hold on
plot(x,y,'-o','markersize',4,'markerfacecolor','r')
plot(xx,yy,'o','markersize',5,'markerfacecolor','g')
xlabel('x')
ylabel('y')
title('Interpolación lineal');
hold off
EJERCICIO 100