Тема8_Matlab
.pdfТема 8
Пример ИКЗ
В файле ML1_13.txt собраны данные о требованиях к твердости различных деталей газовой арматуры. Каждая строка относится к одной из деталей и содержит 2 числа: наименьшее и наибольшее допустимое значение твердости стали для данной детали. Номер строки соответствует номеру, обозначающему деталь. Пользователь должен иметь возможность ввести номер детали и значения измеренной твердости и получить суждение о выполнении или невыполнении требований по твердости. Для уменьшения ошибки в суждениях измерения повторяются 5 раз. При решении задачи по введенным пользователем 5 измерениям твердости необходимо рассчитать среднее арифметическое значение измеренной твердости. Если это среднее окажется между наименьшим и наибольшим допустимыми значениями для данной детали, то выдается суждение «Требования по твердости выполнены», в ином случае – суждение «Требования по твердости не выполнены».
1 способ решения: через командное окно (программа T8_1.m):
Matr=load('ML1_13.txt') while 1
prov=1
while prov==1 n=input('Номер детали: ')
if n<=size(Matr,1) prov=0
else
disp('Детали не обнаружено!') end
end
for i=1:5
d(i)=input(['Измеренное значение твердости № ' num2str(i) ' = '])
end srednee=sum(d)/5
if (Matr(n,1)<=srednee) & (Matr(n,2)>=srednee) k=1
disp('Требования по твердости выполнены') else
k=0
disp('Требования по твердости не выполнены') end
pr=input('Введите 1 для вывода результатов в print1.txt, иначе введите любое другое число: ')
if pr==1 fp=fopen('print1.txt','w')
fprintf(fp,'Деталь № %2.0d \n',n)
fprintf(fp,'Граничные значения твердости от %3.0d до %3.0d \n',Matr(n,1),Matr(n,2))
fprintf(fp,['Измеренные значения: ' num2str(d)]) if k==1
fprintf(fp,'\nСуждение: Требования по твердости выполнены') else
fprintf(fp,'\nСуждение: Требования по твердости не выполнены')
end fclose(fp)
end
cntn=input('Введите 1 для продолжения расчетов, иначе введите любое другое число: ')
if cntn~=1 break
end end
1
2 способ решения: с помощью экранной формы.
1. Главная программа T8_2.m global Matr Nomer Matr=load('ML1_13.txt') Nomer=size(Matr,1) run('detaly.m
2. Экранная форма detaly.fig:
3. Программа detaly.m, обслуживающая экранную форму (файл создается автоматически при создании формы; добавленный код выделен желтым):
function varargout = detaly(varargin)
%DETALY MATLAB code for detaly.fig
%DETALY, by itself, creates a new DETALY or raises the existing
%singleton*.
%
%H = DETALY returns the handle to a new DETALY or the handle to
%the existing singleton*.
%
%DETALY('CALLBACK',hObject,eventData,handles,...) calls the local
%function named CALLBACK in DETALY.M with the given input
arguments.
%DETALY('Property','Value',...) creates a new DETALY or raises the
%existing singleton*. Starting from the left, property value
pairs are
%applied to the GUI before detaly_OpeningFcn gets called. An
%unrecognized property name or invalid value makes property
application
%stop. All inputs are passed to detaly_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 detaly
%Last Modified by GUIDE v2.5 22-Apr-2020 18:47:09
2
% Begin initialization code - DO NOT EDIT gui_Singleton = 1;
gui_State = struct('gui_Name', |
mfilename, ... |
'gui_Singleton', |
gui_Singleton, ... |
'gui_OpeningFcn', |
@detaly_OpeningFcn, ... |
'gui_OutputFcn', |
@detaly_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 detaly is made visible.
function detaly_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 detaly (see VARARGIN) |
% Choose default command line output for detaly handles.output = hObject;
%Update handles structure guidata(hObject, handles);
%UIWAIT makes detaly wait for user response (see UIRESUME)
%uiwait(handles.figure1);
%--- Outputs from this function are returned to the command line. function varargout = detaly_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;
set(handles.text2,'visible','off') set(handles.text3,'visible','off') set(handles.edit2,'visible','off') set(handles.edit3,'visible','off') set(handles.edit4,'visible','off') set(handles.edit5,'visible','off') set(handles.edit6,'visible','off') set(handles.pushbutton1,'visible','off')
function edit1_Callback(hObject, eventdata, handles)
% hObject |
handle to edit1 (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 edit1 as text
%str2double(get(hObject,'String')) returns contents of edit1 as
a double
global n d Nomer d=zeros(1,5)
if isempty(get(hObject,'string')) set(handles.text2,'visible','off') set(handles.text3,'visible','off')
3
set(handles.edit2,'visible','off') set(handles.edit3,'visible','off') set(handles.edit4,'visible','off') set(handles.edit5,'visible','off') set(handles.edit6,'visible','off') set(handles.pushbutton1,'visible','off')
else n=str2num(get(hObject,'string')) if n>Nomer
set(handles.text2,'visible','off') set(handles.edit2,'visible','off') set(handles.edit3,'visible','off') set(handles.edit4,'visible','off') set(handles.edit5,'visible','off') set(handles.edit6,'visible','off') set(handles.pushbutton1,'visible','off') set(handles.text3,'string','Детали не обнаружено!') set(handles.text3,'visible','on')
else set(handles.edit2,'string','') set(handles.edit3,'string','') set(handles.edit4,'string','') set(handles.edit5,'string','') set(handles.edit6,'string','')
set(handles.edit2,'visible','on') set(handles.edit3,'visible','on') set(handles.edit4,'visible','on') set(handles.edit5,'visible','on') set(handles.edit6,'visible','on') set(handles.text2,'visible','on') set(handles.text3,'string','') set(handles.text3,'visible','off') set(handles.pushbutton1,'visible','off')
end
end
% --- Executes during object creation, after setting all properties. function edit1_CreateFcn(hObject, eventdata, handles)
% hObject |
handle to edit1 (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 edit2_Callback(hObject, eventdata, handles)
% hObject |
handle to edit2 (see GCBO) |
% eventdata |
reserved - to be defined in a future version of MATLAB |
% handles |
structure with handles and user data (see GUIDATA) |
global d d(1)=str2num(get(hObject,'string')) if
(~isempty(get(handles.edit2,'string'))&&~isempty(get(handles.edit3,'string')) &&~isempty(get(handles.edit4,'string'))&&~isempty(get(handles.edit5,'string') )&&~isempty(get(handles.edit6,'string')))
set(handles.pushbutton1,'visible','on') set(handles.text3,'visible','off')
end
% Hints: get(hObject,'String') returns contents of edit2 as text
4
%str2double(get(hObject,'String')) returns contents of edit2 as
a double
%--- Executes during object creation, after setting all properties. function edit2_CreateFcn(hObject, eventdata, handles)
% hObject |
handle to edit2 (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 edit3_Callback(hObject, eventdata, handles)
% hObject |
handle to edit3 (see GCBO) |
% eventdata |
reserved - to be defined in a future version of MATLAB |
% handles |
structure with handles and user data (see GUIDATA) |
global d d(2)=str2num(get(hObject,'string')) if
(~isempty(get(handles.edit2,'string'))&&~isempty(get(handles.edit3,'string')) &&~isempty(get(handles.edit4,'string'))&&~isempty(get(handles.edit5,'string') )&&~isempty(get(handles.edit6,'string')))
set(handles.pushbutton1,'visible','on') set(handles.text3,'visible','off')
end
%Hints: get(hObject,'String') returns contents of edit3 as text
%str2double(get(hObject,'String')) returns contents of edit3 as
a double
%--- Executes during object creation, after setting all properties. function edit3_CreateFcn(hObject, eventdata, handles)
% hObject |
handle to edit3 (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 edit4_Callback(hObject, eventdata, handles)
% hObject |
handle to edit4 (see GCBO) |
% eventdata |
reserved - to be defined in a future version of MATLAB |
% handles |
structure with handles and user data (see GUIDATA) |
global d d(3)=str2num(get(hObject,'string')) if
(~isempty(get(handles.edit2,'string'))&&~isempty(get(handles.edit3,'string')) &&~isempty(get(handles.edit4,'string'))&&~isempty(get(handles.edit5,'string') )&&~isempty(get(handles.edit6,'string')))
set(handles.pushbutton1,'visible','on') set(handles.text3,'visible','off')
end
%Hints: get(hObject,'String') returns contents of edit4 as text
%str2double(get(hObject,'String')) returns contents of edit4 as
a double
%--- Executes during object creation, after setting all properties.
5
function edit4_CreateFcn(hObject, eventdata, handles)
% hObject |
handle to edit4 (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 edit5_Callback(hObject, eventdata, handles)
% hObject |
handle to edit5 (see GCBO) |
|
% eventdata |
reserved - to be defined in a future version of MATLAB |
|
% handles |
structure with handles and user data (see GUIDATA) |
|
global d |
|
|
d(4)=str2num(get(hObject,'string')) if
(~isempty(get(handles.edit2,'string'))&&~isempty(get(handles.edit3,'string')) &&~isempty(get(handles.edit4,'string'))&&~isempty(get(handles.edit5,'string') )&&~isempty(get(handles.edit6,'string')))
set(handles.pushbutton1,'visible','on') set(handles.text3,'visible','off')
end
%Hints: get(hObject,'String') returns contents of edit5 as text
%str2double(get(hObject,'String')) returns contents of edit5 as
a double
%--- Executes during object creation, after setting all properties. function edit5_CreateFcn(hObject, eventdata, handles)
% hObject |
handle to edit5 (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 edit6_Callback(hObject, eventdata, handles)
% hObject |
handle to edit6 (see GCBO) |
|
% eventdata |
reserved - to be defined in a future version of MATLAB |
|
% handles |
structure with handles and user data (see GUIDATA) |
|
global d |
|
|
d(5)=str2num(get(hObject,'string')) if
(~isempty(get(handles.edit2,'string'))&&~isempty(get(handles.edit3,'string')) &&~isempty(get(handles.edit4,'string'))&&~isempty(get(handles.edit5,'string') )&&~isempty(get(handles.edit6,'string')))
set(handles.pushbutton1,'visible','on') set(handles.text3,'visible','off')
end
%Hints: get(hObject,'String') returns contents of edit6 as text
%str2double(get(hObject,'String')) returns contents of edit6 as
a double
%--- Executes during object creation, after setting all properties.
6
function edit6_CreateFcn(hObject, eventdata, handles)
% hObject |
handle to edit6 (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 pushbutton1.
function pushbutton1_Callback(hObject, eventdata, handles)
% hObject |
handle to pushbutton1 (see GCBO) |
% eventdata |
reserved - to be defined in a future version of MATLAB |
% handles |
structure with handles and user data (see GUIDATA) |
global Matr d n k srednee=sum(d)/5
if (Matr(n,1)<=srednee) && (Matr(n,2)>=srednee) k=1
set(handles.text3,'string','Требования по твердости выполнены') set(handles.text3,'visible','on')
else k=0
set(handles.text3,'string','Требования по твердости не
выполнены')
set(handles.text3,'visible','on')
end fp=fopen('print2.txt','w')
fprintf(fp,'Деталь № %2.0d \n',n)
fprintf(fp,'Граничные значения твердости от %3.0d до %3.0d \n',Matr(n,1),Matr(n,2))
fprintf(fp,'Измеренные значения:%s ',num2str(d)) if k==1
fprintf(fp,'\nСуждение: Требования по твердости выполнены') else
fprintf(fp,'\nСуждение: Требования по твердости не выполнены')
end
fclose(fp)
7