Anda di halaman 1dari 9

INTEGRACION DE DATOS CON SPLINE

Spline: Es una determinada curva diferenciable definida en una cantidad de porciones mediante
polinomios. Se usa a menudo en la interpolación porque da lugar a resultados precisos requiriendo
solamente del uso de polinomios de bajo grado evitando así las pequeñas distorsiones u
oscilaciones que se pueden presentar.

Ejemplo de un tipo de Spline

Para poder integrar con Spline necesitamos hallar el polinomio de interpolación. Supóngase que se
va a interpolar cierta función f(ti) definida por un conjunto finito de valores yi por medio de unas
serie de polinomios pi(t).Cabe decir que los datos t0,t1,…,ti-1,ti ,ti+1,…,tn-1,tn; no tienen que estar
necesariamente igualmente espaciados , pero deben cumplir con la condición:

De modo que el objetivo es encontrar los polinomios pi (t) que interpole la función yi= f(ti) en un
intervalo [ti, ti+1], con i=1,2,3,…,n-1.

Interpolación de una función f(ti)

También hay que tener en cuenta que se debe cumplir lo siguiente:


Para que la función no tenga cambios bruscos sus derivadas en los extremos de los polinomios de
cada respectivo tramo deben coincidir al igual que su segunda derivada, con el fin de mantener
una continuidad en la curva final obtenida:

Las dos tipos de interpolación con Spline que utilizaremos son la lineal y cubica. La lineal se rige
bajo la fórmula:

La cubica se rige a partir de todas las condiciones nombradas anteriormente y bajo la fórmula:

en la cual:

Interfaz del método integración de datos con Spline en matlab


1. En este cuadro colocamos la cantidad de filas o valores variables que tendrá la interpolación

2. Estos dos botones me permitirán calcular la integral con los datos y poder modificar la entrada
de valores sin necesidad de tener que volver al inicio de la interfaz

3. En este recuadro se mostrara la gráfica de la interpolación con Spline

4. En estos cuadros se podrá los dos resultados de la integral con Spline, una con interpolación
lineal y la otra con interpolación cubica

5. Con estos dos botones podemos devolvernos a la ventana de la interfaz principal y salirnos por
completo del programa

Ejemplo:
Código de la interfaz:
integracion_spline.m

function varargout = integracion_spline(varargin)


% INTEGRACION_SPLINE MATLAB code for integracion_spline.fig
% INTEGRACION_SPLINE, by itself, creates a new INTEGRACION_SPLINE or
raises the existing
% singleton*.
%
% H = INTEGRACION_SPLINE returns the handle to a new
INTEGRACION_SPLINE or the handle to
% the existing singleton*.
%
% INTEGRACION_SPLINE('CALLBACK',hObject,eventData,handles,...) calls
the local
% function named CALLBACK in INTEGRACION_SPLINE.M with the given
input arguments.
%
% INTEGRACION_SPLINE('Property','Value',...) creates a new
INTEGRACION_SPLINE or raises the
% existing singleton*. Starting from the left, property value pairs
are
% applied to the GUI before integracion_spline_OpeningFcn gets
called. An
% unrecognized property name or invalid value makes property
application
% stop. All inputs are passed to integracion_spline_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

% Edit the above text to modify the response to help integracion_spline

% Last Modified by GUIDE v2.5 17-May-2018 16:18:40

% Begin initialization code - DO NOT EDIT


gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @integracion_spline_OpeningFcn, ...
'gui_OutputFcn', @integracion_spline_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 integracion_spline is made visible.


function integracion_spline_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 integracion_spline (see VARARGIN)

% Choose default command line output for integracion_spline


handles.output = hObject;

% Update handles structure


guidata(hObject, handles);

% UIWAIT makes integracion_spline wait for user response (see UIRESUME)


% uiwait(handles.figure1);

% --- Outputs from this function are returned to the command line.
function varargout = integracion_spline_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;

% --- Executes on button press in calcular.


function calcular_Callback(hObject, eventdata, handles)
% hObject handle to calcular (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
cla(handles.axes1);
datos=get(handles.uitable1, 'Data');
x=datos(:,1);
y=datos(:,2);

for i=1:size(x)
if isnan(x(i)) || isnan(y(i))
set(handles.mensajes,'string','Error: datos en la tabla son
invalidos');
set(handles.integracion_lineal,'string','NaN');
set(handles.integracion_cubica,'string','NaN');
return;
end
end
[I_cubica, I_lineal, mensaje]=inter_spline(x,y);
set(handles.mensajes,'string',mensaje);
set(handles.integracion_lineal,'string',I_lineal);
set(handles.integracion_cubica,'string',I_cubica);

% --- Executes on button press in limpiar.


function limpiar_Callback(hObject, eventdata, handles)
% hObject handle to limpiar (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
set(handles.integracion_lineal,'string','');
set(handles.integracion_cubica,'string','');
set(handles.filas,'string','');
set(handles.uitable1, 'Data',zeros(4,2));
set(handles.mensajes,'string','');
cla(handles.axes1)

% --- Executes on button press in salir.


function salir_Callback(hObject, eventdata, handles)
% hObject handle to salir (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
close(integracion_spline);

% --- Executes on button press in volver.


function volver_Callback(hObject, eventdata, handles)
% hObject handle to volver (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
menu_principal;
close(integracion_spline);
function integracion_lineal_Callback(hObject, eventdata, handles)
% hObject handle to integracion_lineal (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of integracion_lineal as


text
% str2double(get(hObject,'String')) returns contents of
integracion_lineal as a double

% --- Executes during object creation, after setting all properties.


function integracion_lineal_CreateFcn(hObject, eventdata, handles)
% hObject handle to integracion_lineal (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 && isequal(get(hObject,'BackgroundColor'),
get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end

function integracion_cubica_Callback(hObject, eventdata, handles)


% hObject handle to integracion_cubica (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of integracion_cubica as


text
% str2double(get(hObject,'String')) returns contents of
integracion_cubica as a double

% --- Executes during object creation, after setting all properties.


function integracion_cubica_CreateFcn(hObject, eventdata, handles)
% hObject handle to integracion_cubica (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 && isequal(get(hObject,'BackgroundColor'),
get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function filas_Callback(hObject, eventdata, handles)
% hObject handle to filas (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of filas as text


% str2double(get(hObject,'String')) returns contents of filas as a
double

% --- Executes during object creation, after setting all properties.


function filas_CreateFcn(hObject, eventdata, handles)
% hObject handle to filas (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 && isequal(get(hObject,'BackgroundColor'),
get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end

% --- Executes on button press in crear_filas.


function crear_filas_Callback(hObject, eventdata, handles)
% hObject handle to crear_filas (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
filas=str2double(get(handles.filas, 'string'));
if isnan(filas)
set(handles.mensajes,'string','Error: numero de filas invalido');
return;
end
ancho=80;%Elegimos el ancho de las columnas en nuestra tabla
ancho_col=num2cell(ancho*ones([1 filas]));%Creamos celdas para pasar a la
tabla
formato_col = cell(1, filas);%creamos celdas para pasar al tipo de dato
de la tabla
formato_col(:)={'numeric'};
set(handles.uitable1, 'Data',zeros(filas,2));
set(handles.uitable1, 'ColumnWidth', ancho_col);
set(handles.uitable1, 'ColumnFormat', formato_col);

inter_spline.m

function [I_cubica, I_lineal, mensaje]=inter_spline(x,y)


%Aproximacion de la integral de unos datos x e y utilizando spline
%con una interpolacion lineal y cubica
%Variables de entrada:
% x: datos sobre el eje x
% y: imagenes de x en el eje y
% Variables de salida:
% I_cubica: integral aproximada utilizando una interpolacion cubica
% I_lineal: integral aproximada utilizando una interpolacion lineal
% mensaje: mensaje de error o de solucion

mensaje='Solucionado';
I_cubica=NaN; %Inizializar valores en caso de error
I_lineal=NaN;
%x=[-2 -1 0 1 2 3];
%y=[1 4 11 16 13 -4];

try
pp=spline(x,y);
I_cubica=integral(@(x) ppval(pp,x),min(x),max(x)); %integral con
interpolacion cubica
I_lineal=trapz(x,y); %integral con interpolacion lineal
catch
mensaje='Error: los datos no se pueden integrar';
return;
end

try

plot(x,y,'x','markersize',6,'markerfacecolor','g','DisplayName','Datos de
entrada'); %gráfica los datos
grid on
hold on

xx=linspace(min(x),max(x),100); %Datos para graficar la curva


yy=ppval(pp,xx);
plot(xx,yy,'--','DisplayName','Interpolacion
spline','Linewidth',1.5);
xlabel('Eje X');
ylabel('Eje Y');
legend
catch
mensaje='Error: los datos no se pueden graficar';
return;
end

Anda mungkin juga menyukai