Clases de Matlab

Enviado por Programa Chuletas y clasificado en Informática y Telecomunicaciones

Escrito el en español con un tamaño de 27,26 KB

 
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%5
% Primer archivo de MatLab
% Creacion y manipulación de vectores y matrices
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Entradas:
%
% Salidas:
%
clc
% Creacion de vectores
a=6.5;
% El punto y coma evita la visualizacion en pantalla
B=[1
2
2];
plot(B);
hold
on;
t=0:100;
% Crea un vector de 0 a 100 (paso de 1 en 1)
x=2*t+20;
%
plot(t,x);
y=-(t-10).*(t-70);
plot(t,y);

% Creacion de matrices
 
A=[1 3 4
2 4 0
2 1 1]
A'
A*(A')
A'*A
M=[-3 4
0 -6]
M*(M')
M'*M

% Clase 03
% Primeros programas con el MatLab
% Uso de la linea de comandos con el "Editor de Scripts"
% Indice
% 1. Repaso de los comandos vistos en la Clase02 (help, plot, hold)
% 2. Grafica de funciones senoidales y almacenamiento de graficas
% 3. Ingreso de datos pedidos por el programa
 
clc
% Limpiar pantalla (clear screen)
close
all % Cierra todas las ventanas existente (excepto el editor)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% 1. Repaso de los comandos vistos en la Clase02 (help, plot, hold)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
 
t=0:1:100;
% Pasos de 1 en 1 desde 0 hasta 100
f=-(t-10).*(t-70);
% .* es producto punto a punto
g=-2*(t-10).*(t-70);
% ; para indicar que no se presente el resultado en pantalla
 
plot(t,f);
hold
on; % Comando para preservar la grafica anterior
plot(t,g,
'r') % 'r' se indica que grafique la curva en color rojo
grid
on;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% 2. Grafica de funciones senoidales y almacenamiento de graficas
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
 
% partiendo de que el MatLab difirencia mayusculas de minusculas F,G en
% funcion de X
figure;
% Se crea una nueva ventana para las figuras
 
% x=0:1:2; % Pasos de pi en pi desde 0 hasta 2*pi
% Para definir el numero el numero de puntos, usaremos "linspace"
x=linspace(0,2,4);
% nro de elementos del vector : 4
F=sin(pi*x);
plot(x,F);
% AZUL ¡¡¡ Cuidar que las abcisas y ordenadas tengan la misma longitud
hold
on;
x=linspace(0,2,5);
% nro de elementos del vector : 5
F=sin(pi*x);
plot(x,F,
'r'); % 'r' rojo
hold
on;
x=linspace(0,2,10);
% nro de elementos del vector : 10
F=sin(pi*x);
plot(x,F,
'g'); % 'g' verde
hold
on;
x=linspace(0,2,1000);
% nro de elementos del vector : 1000
F=sin(pi*x);
plot(x,F,
'k'); % 'k' negro
 
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% 3. Ingreso de datos pedidos por el programa
% Sera por medio de la linea de comandos --> input
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
 
peras= 150

manzana=input(
'¿ Cuantas manzanas quiere ? ');
'Costo en soles'
manzana*0.5

muestreo=input(
'¿ Cuantos puntos de muestreo quiere visualizar para "sen(pi.x)" ? ');
figure;
x=linspace(0,2,muestreo);
% nro de elementos del vector : muestreo
F=sin(pi*x);
plot(x,F,
'g'); % 'g' verde
hold
on;




% Clase 04
% Primeros programas con el MatLab
% Uso de la linea de comandos con el "Editor de Scripts"
% Indice
% 1. Serie de Fibonacci
% 2.
 
clc
% Limpiar pantalla (clear screen)
close
all % Cierra todas las ventanas existente (excepto el editor)
clear
all % Borra o elimina de memoria todas sus variables
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% 1. Serie de Fibonacci
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
x(1)=1;
% Primera condicion inicial
x(2)=1;
% Segunda condicion inicial
n=input(
'Ingrese el nùmero de tèrminos de Fibonacci = ')
for i=3:n
x(i)=x(i-1)+x(i-2);
% La serie de Fibonacci
end;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% 2. Serie
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
y(1)=-1;
% Primera condicion inicial
y(2)=2;
% Segunda condicion inicial
y(3)=1;
% Tercera condicion inicial
n=input(
'Ingrese el nùmero de tèrminos de la serie = ')
for i=4:n
y(i)=y(i-1)+2*y(i-2)+3*y(i-3);
% La serie
end;
nro=input(
'Ingrese el nùmero de tèrmino a mostrar = ')
y(nro)

plot(x);
hold
on;
plot(y,
'r');


% Clase 05
% Primeros programas con el MatLab
% Uso de la linea de comandos con el "Editor de Scripts"
% Indice
% 1. Repaso de algunos comando
% 2.
 
clc
% Limpiar pantalla (clear screen)
close
all % Cierra todas las ventanas existente (excepto el editor)
clear
all % Borra o elimina de memoria todas sus variables
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% 1. Repaso de algunos comandos
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
a=linspace(2,3);
% Comenzando con el comando linspace
                % se generaron 100 elmentos distanciados entre si 1/99
b=linspace(2,3,101);
% Comenzando con el comando linspace
                % se generaron 101 elementos distanciados entre si 1/100
c=2:(1/100):3;
% Es una manera mas rapida de generar elementos distanciados entre si 1/100
 
usb=input(
'Cuantos arboles desea talar = '); % El comando input como ingreso de variables
 
 
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% 2. Series con el comando symsum
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
 
syms
k  % Definir la variable 'k' de forma simbolica
symsum(1/(k^3),1,Inf);
symsum(1/(k^4),1,Inf);
symsum(1/(k^6),1,Inf);


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% 3. Ver mas sobre creacion y manipulacion de matrices
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
 
A=[1 .2 5
3 5 .8
4 .7 .8]
A*(A');
(A')*A;
% Visto en la clase 02
 
B=[10 20 50
30 50 80
40 70 80]
A+B
A*B
A.*B
A^2
A, A^2, A^5000
A-B

ones(3)
zeros(3)
eye(3)
eye(3,6)

rand(3)
rand(6,3)
10*rand(6,3)
Maleatoria=100*rand(6,3)
round(Maleatoria)


% Clase 06
% Programas con el MatLab
% Uso de la linea de comandos con el "Editor de Scripts"
% Indice
% 1. Repaso de comandos
% 2. Un prograMA QUE MANEJA GRÀFICOS
 
clc
% Limpiar pantalla (clear screen)
close
all % Cierra todas las ventanas existente (excepto el editor)
clear
all % Borra o elimina de memoria todas sus variables
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% 1. Repaso de algunos comandos
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
X=1:1:5
% Sea crea el vector X que va desde 1 hasta 5 con pasos de 1 en 1
Y=[-1 1 2 2.2 2.3];
% Sea crea el vector Y
plot(X,Y)
hold
on;
xmejorado=1:1:10;
ymejorado=[-1 .1 1 1.5 2 2.1 2.2 2.25 2.3 2.31]
plot(xmejorado,ymejorado,
'r');
xmejorado_ver2=linspace(1,5,10);
plot(xmejorado_ver2,ymejorado,
'g');

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% 2. Un prograMA QUE MANEJA GRÀFICOS
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
figure;
line([1 4],[2 7]);
hold
on;
line([1 4 5],[2 7 3])
hold
on;
line([1 4 5 1],[2 7 3 1.8])

figure;
subplot(3,1,1);
line([1 4],[2 7]);
xlabel(
'X');
ylabel(
'Y');
title(
'Gráfico de una línea (vector) en 2-D')
subplot(3,1,2);
line([1 4 5],[2 7 3])
subplot(3,1,3);
line([1 4 5 1],[2 7 3 1.8])

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% 3. Dibujando un arbolito (imaginar que es una troncal, con varias ramas,
% cada una de las cuales tiene sub-ramas, y cada una de las cuales tiene varias
% hojas o dispositivos conectadas a ella)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
clear
all
clc
close
all
figure;
hold
on; % Para preservar en el gráfico c/u de las línea a graficar
x=[0
0];
y=[0
rand]
line(x,y);
% El tronco del arbol
n=12
for i=1:n
[m, longi]=size(x);
% Capturamos el tamaño de x (inicial/e 2x1)
angu1=(pi/2)*rand(1,longi);
angu2=(pi/2)*rand(1,longi)+angu1;
x=[x(2,:) x(2,:)
x(2,:)+(2/i)*rand*cos(angu1) x(2,:)+(3/i)*rand*cos(angu2)];
y=[y(2,:) y(2,:)
y(2,:)+(2/i)*rand*sin(angu1) y(2,:)+(3/i)*rand*sin(angu2)];
line(x,y)
end;

clear
all
clc
close
all
int(
'x^2')


%otros
function b=creamatriz(nfilas,ncolumnas,fila)
b=rand(nfilas,ncolumnas);
stem(b(:,fila));



% Problema
% halle la serie de fourier de la funcion definida por
% f(x)=0, -pi<=x<0
% f(x)=pi, 0<=x
 
clc
% Limpiar pantalla
clear
all   % Borrar todas las variables
m=input(
'diga cuantos sumando quiere que tenga su serie de fourier= ');
% Se ingresa por teclado la variable 'm'
syms
n; % Definir la variable 'n' de forma simbolica
x=-pi:0.1:pi;
% Crear un vector fila de -pi a pi con paso de 0.1
sum=symsum(sin((2*n-1)*x)/(2*n-1),n,1,m);
f=double(pi/2+2*sum);
plot(x,f);
grid
on
 
 
 
 
xn=-3.1:0.1:0
xp=.1:.1:3.1
hold
on
plot(xn,zeros(1,length(xn)),
'r',xp,pi*ones(1,length(xp)),'r')



% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %Programa grafico realizado para ver el desarrollo de la serie de la %
% % Fourier para la funcion: %
% % f(x)=0,-pi
% % f(x)=pi,0<=x<=pi %
% % Las constantes fueron halladas en el libro Calculo de Simmons, en el %
% % capitulo que trata sobre el desarrollo de la serie de Fourier %
% % AUTOR:Carlos Chuquillanqui Gamarra CODIGO:0820249 %
% % E-MAIL:[email protected] %
% % [email protected] %
% % Se aceptan sugerencias y criticas, el codigo puede ser usado %
% % y modificado a voluntad por los estudiantes %
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
 
 
function varargout = fourier1(varargin)
% FOURIER1 M-file for fourier1.fig
% FOURIER1, by itself, creates a new FOURIER1 or raises the existing
% singleton*.
%
% H = FOURIER1 returns the handle to a new FOURIER1 or the handle to
% the existing singleton*.
%
% FOURIER1('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in FOURIER1.M with the given input arguments.
%
% FOURIER1('Property','Value',...) creates a new FOURIER1 or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before fourier1_OpeningFunction gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to fourier1_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
 
% Copyright 2002-2003 The MathWorks, Inc.
 
% Edit the above text to modify the response to help fourier1
 
% Last Modified by GUIDE v2.5 14-Jul-2008 22:36:34
 
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct(
'gui_Name', mfilename, ...
                   'gui_Singleton', gui_Singleton, ...
                   'gui_OpeningFcn', @fourier1_OpeningFcn, ...
                   'gui_OutputFcn', @fourier1_OutputFcn, ...
                   'gui_LayoutFcn', [] , ...
                   'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
 
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
 
 
% --- Executes just before fourier1 is made visible.
function fourier1_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to fourier1 (see VARARGIN)
clear
x y f g;
x=-pi:0.01:0;
f=0;
y=0:0.01:pi;
g=pi;
plot(x,f,
'r')
hold
plot(y,g,
'r')
grid ;
hold
off;

% Choose default command line output for fourier1
handles.output = hObject;

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes fourier1 wait for user response (see UIRESUME)
% uiwait(handles.figure1);
 
 
% --- Outputs from this function are returned to the command line.
function varargout = fourier1_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)
 
% Get default command line output from handles structure
varargout{1} = handles.output;





function numero_Callback(hObject, eventdata, handles)
% hObject handle to numero (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
num = get(hObject,
'String');% returns contents of numero as text
% str2double(get(hObject,'String')) returns contents of numero as a
% double
clear
n x sum f y h g z;
x=-pi:0.01:0;
f=0;
y=0:0.01:pi;
g=pi;
plot(x,f,
'r')
hold
on
plot(y,g,
'r')
syms
n;
z=-pi:0.1:pi;
sum=symsum(sin((2*n-1)*z)/(2*n-1),n,1,num);
h=double(pi/2+2*sum);
plot(z,h)
grid
on;
hold
off
set(hObject,
'String','')
% --- Executes during object creation, after setting all properties.
function numero_CreateFcn(hObject, eventdata, handles)
% hObject handle to numero (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
 
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc
set(hObject,
'BackgroundColor','white');
else
set(hObject,
'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
 

Entradas relacionadas: