4. Выполнение работы
Нам нужно сделать программу в среде guide, которая будет строить график функции, которую должен задать пользователь. Функции можно добавлять в отдельный список и удалять их оттуда. Для этого нам нужно зайти в среду guide и перетащить в заготовку окна приложения елементы интерфейса которые мы будем использовать (рис 4.1).
Рис.4.1
В нашем задании мы нспользуем следующие елементы интерфейса: Edit Text(поле для ввода текста 3 штуки), Push button( кнопки 3 штуки), Static Text(текстовая область, используется для описания), Axes(оси) и List Box( список куда мы будем добавлять функции).
Рис. 4.2.
На рисунке 4.2 мы видим что полозователь вводит даные для построения графика, а именно: любую функцию и интервал на котором будет строится график. Слева мы видим область где строится сам график, а справа список, куда можно добавлять функции и выбирать их остуда для построения. Снизу мы види 3 кнопки: добавление в список, очищение графика, очищение самого списка.
Код программы:
function varargout = Laba2(varargin)
% LABA2 M-file for Laba2.fig
% LABA2, by itself, creates a new LABA2 or raises the existing
% singleton*.
%
% H = LABA2 returns the handle to a new LABA2 or the handle to
% the existing singleton*.
%
% LABA2('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in LABA2.M with the given input arguments.
%
% LABA2('Property','Value',...) creates a new LABA2 or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before Laba2_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to Laba2_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 Laba2
% Last Modified by GUIDE v2.5 13-Apr-2012 15:35:24
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @Laba2_OpeningFcn, ...
'gui_OutputFcn', @Laba2_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 Laba2 is made visible.
function Laba2_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 Laba2 (see VARARGIN)
% Choose default command line output for Laba2
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes Laba2 wait for user response (see UIRESUME)
% uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.
function varargout = Laba2_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 hBadd.
function varargout=hBadd_Callback(hObject, eventdata, handles)
% hObject handle to hBadd (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
f1=get(handles.hEdit,'String'); %Заданую функцію записываем в f1.
f2=get(handles.hList,'String'); %Записываем содержание списка в f2.
aStr=get(handles.hEdit1,'String');%Записываем начало промежутка в aStr.
bStr=get(handles.hEdit2,'String');%Записываем конец промежутка в bStr.
a=str2num(aStr);% Приведение в целочисельный тип.
b=str2num(bStr);% Приведение в целочисельный тип.
f2{end+1}=f1; % Добавляем в конец масива f2 масив f1.
fplot(f1,[a,b]);% Строим график по нашей зданой функции.
set(handles.hList,'String',f2);% Добавлем масив f2 с старыми и новой функцией в список.
set(handles.hBclear, 'Enable', 'on');% Делает активной кнопку Clear.
set(handles.hBclrL, 'Enable', 'on'); % Делает активной кнопку Clear list.
uicontrol(handles.hEdit) % Передает фокус строке в которую вписывается функция.
% --- Executes on button press in hBclear.
function hBclear_Callback(hObject, eventdata, handles)
% hObject handle to hBclear (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
cla; % Очищает координатные оси.
set(handles.hEdit, 'String', '');%Очищает строку для функции.
set(handles.hEdit1, 'String', '');% Очищает строку для начала промежутка.
set(handles.hEdit2, 'String', '');% ОЧищает строку для конца промежутка.
set(handles.hBclear, 'Enable', 'off');% Делает неактивной кнопку Clear.
set(handles.hBadd, 'Enable', 'off');% Делает неактивной кнопку Add.
uicontrol(handles.hEdit)% передает фокус строке в которую вписуется функция.
function hEdit_Callback(hObject, eventdata, handles)
% hObject handle to hEdit (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 hEdit as text
% str2double(get(hObject,'String')) returns contents of hEdit as a double
uicontrol(handles.hEdit1);% передает фокус строке где указывается начало промежутка.
% --- Executes during object creation, after setting all properties.
function hEdit_CreateFcn(hObject, eventdata, handles)
% hObject handle to hEdit (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 selection change in hList.
function hList_Callback(hObject, eventdata, handles)
% hObject handle to hList (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
k=get(handles.hList,'Value');% Записываем в переменную k значения выбраной строки в списке.
f=get(handles.hList,'String');% Записываем в переменную f весь массив который находится в списке.
f1=char(f(k));% Записываем в f1 выбраное значение со списка приводя его к типу строки.
set(handles.hEdit,'String',f1);% Устанавливаем выбраную функцію в строку ввода.
set(handles.hEdit1,'String',-10);% Устанавливаем начало промежутка.
set(handles.hEdit2,'String',10);% Устанавливаем конец промежутка.
fplot(f1,[-10,10]);% Рисуем график заданой функции в заданом промежутке.
uicontrol(handles.hEdit);% передает фокус строке где указывается начало промежутка.
% Hints: contents = get(hObject,'String') returns hList contents as cell array
% contents{get(hObject,'Value')} returns selected item from hList
% --- Executes during object creation, after setting all properties.
function hList_CreateFcn(hObject, eventdata, handles)
% hObject handle to hList (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: listbox 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 hEdit1_Callback(hObject, eventdata, handles)
% hObject handle to hEdit1 (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 hEdit1 as text
% str2double(get(hObject,'String')) returns contents of hEdit1 as a double
uicontrol(handles.hEdit2);% передает фокус началу промежутка.
% --- Executes during object creation, after setting all properties.
function hEdit1_CreateFcn(hObject, eventdata, handles)
% hObject handle to hEdit1 (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 hEdit2_Callback(hObject, eventdata, handles)
% hObject handle to hEdit2 (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 hEdit2 as text
% str2double(get(hObject,'String')) returns contents of hEdit2 as a double
set(handles.hBadd, 'Enable', 'on');% Делает активную кнопку Add.
uicontrol(handles.hBadd);% передает фокус этой кнопки.
% --- Executes during object creation, after setting all properties.
function hEdit2_CreateFcn(hObject, eventdata, handles)
% hObject handle to hEdit2 (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 hBclrL.
function hBclrL_Callback(hObject, eventdata, handles)
% hObject handle to hBclrL (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
set(handles.hList, 'String', '');% Очищает список.
set(handles.hBclrL, 'Enable', 'off');% Делает неактивной кнопку очистки списка.
% --- Executes on key press with focus on hList and none of its controls.
function hList_KeyPressFcn(hObject, eventdata, handles)
% hObject handle to hList (see GCBO)
% eventdata structure with the following fields (see UICONTROL)
% Key: name of the key that was pressed, in lower case
% Character: character interpretation of the key(s) that was pressed
% Modifier: name(s) of the modifier key(s) (i.e., control, shift) pressed
% handles structure with handles and user data (see GUIDATA)
% --- If Enable == 'on', executes on mouse press in 5 pixel border.
% --- Otherwise, executes on mouse press in 5 pixel border or over hList.
function hList_ButtonDownFcn(hObject, eventdata, handles)
% hObject handle to hList (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)