Создать программы с графическим интерфейсом с использованием компонента RaduioButton для…
- User
Создать программы с графическим интерфейсом с использованием компонента RaduioButton для переключения режима вывода данных согласно варианту и режима изменения данных для расчёта на языке scilab
- Assistant
Вот пример программы на Scilab с графическим интерфейсом, использующей RadioButton для переключения режимов:
// Программа с GUI и RadioButton для переключения режимов clear; clc; close; // Глобальные переменные global output_mode calc_mode; output_mode = 1; // 1-таблица, 2-график, 3-текст calc_mode = 1; // 1-линейный, 2-квадратичный, 3-кубический // Создание главного окна fig = figure('position', [100 100 800 600], ... 'figure_name', 'Программа с переключением режимов', ... 'BackgroundColor', [0.9 0.9 0.9]); // Создание фреймов для группировки элементов // Фрейм для режима вывода frame_output = uicontrol(fig, 'style', 'frame', ... 'position', [20 450 250 120], ... 'BackgroundColor', [0.85 0.85 0.85]); uicontrol(fig, 'style', 'text', ... 'position', [30 540 230 20], ... 'string', 'Режим вывода данных:', ... 'horizontalalignment', 'left', ... 'BackgroundColor', [0.85 0.85 0.85]); // RadioButton для режима вывода radio_table = uicontrol(fig, 'style', 'radiobutton', ... 'position', [40 510 200 20], ... 'string', 'Таблица', ... 'value', 1, ... 'callback', 'output_mode=1; update_radio_output();'); radio_graph = uicontrol(fig, 'style', 'radiobutton', ... 'position', [40 480 200 20], ... 'string', 'График', ... 'value', 0, ... 'callback', 'output_mode=2; update_radio_output();'); radio_text = uicontrol(fig, 'style', 'radiobutton', ... 'position', [40 450 200 20], ... 'string', 'Текстовый вывод', ... 'value', 0, ... 'callback', 'output_mode=3; update_radio_output();'); // Фрейм для режима расчёта frame_calc = uicontrol(fig, 'style', 'frame', ... 'position', [20 300 250 120], ... 'BackgroundColor', [0.85 0.85 0.85]); uicontrol(fig, 'style', 'text', ... 'position', [30 390 230 20], ... 'string', 'Режим расчёта:', ... 'horizontalalignment', 'left', ... 'BackgroundColor', [0.85 0.85 0.85]); // RadioButton для режима расчёта radio_linear = uicontrol(fig, 'style', 'radiobutton', ... 'position', [40 360 200 20], ... 'string', 'Линейная функция (y=ax+b)', ... 'value', 1, ... 'callback', 'calc_mode=1; update_radio_calc();'); radio_quad = uicontrol(fig, 'style', 'radiobutton', ... 'position', [40 330 200 20], ... 'string', 'Квадратичная (y=ax²+bx+c)', ... 'value', 0, ... 'callback', 'calc_mode=2; update_radio_calc();'); radio_cubic = uicontrol(fig, 'style', 'radiobutton', ... 'position', [40 300 200 20], ... 'string', 'Кубическая (y=ax³+bx²+cx+d)', ... 'value', 0, ... 'callback', 'calc_mode=3; update_radio_calc();'); // Поля ввода параметров uicontrol(fig, 'style', 'text', ... 'position', [30 250 100 20], ... 'string', 'Параметры:', ... 'horizontalalignment', 'left'); // Метки и поля ввода uicontrol(fig, 'style', 'text', ... 'position', [30 220 30 20], ... 'string', 'a ='); edit_a = uicontrol(fig, 'style', 'edit', ... 'position', [65 220 50 20], ... 'string', '2'); uicontrol(fig, 'style', 'text', ... 'position', [130 220 30 20], ... 'string', 'b ='); edit_b = uicontrol(fig, 'style', 'edit', ... 'position', [165 220 50 20], ... 'string', '3'); uicontrol(fig, 'style', 'text', ... 'position', [30 190 30 20], ... 'string', 'c ='); edit_c = uicontrol(fig, 'style', 'edit', ... 'position', [65 190 50 20], ... 'string', '1'); uicontrol(fig, 'style', 'text', ... 'position', [130 190 30 20], ... 'string', 'd ='); edit_d = uicontrol(fig, 'style', 'edit', ... 'position', [165 190 50 20], ... 'string', '0'); // Диапазон X uicontrol(fig, 'style', 'text', ... 'position', [30 150 100 20], ... 'string', 'Диапазон X:'); uicontrol(fig, 'style', 'text', ... 'position', [30 120 40 20], ... 'string', 'От:'); edit_xmin = uicontrol(fig, 'style', 'edit', ... 'position', [75 120 50 20], ... 'string', '-10'); uicontrol(fig, 'style', 'text', ... 'position', [130 120 40 20], ... 'string', 'До:'); edit_xmax = uicontrol(fig, 'style', 'edit', ... 'position', [175 120 50 20], ... 'string', '10'); // Кнопка расчёта btn_calc = uicontrol(fig, 'style', 'pushbutton', ... 'position', [50 50 170 40], ... 'string', 'Выполнить расчёт', ... 'callback', 'perform_calculation()'); // Область вывода результатов axes_result = newaxes(); axes_result.margins = [0.1 0.1 0.1 0.1]; axes_result.axes_bounds = [0.4 0.1 0.55 0.8]; // Функции обновления RadioButton function update_radio_output() global output_mode; radio_table.value = (output_mode == 1); radio_graph.value = (output_mode == 2); radio_text.value = (output_mode == 3); endfunction function update_radio_calc() global calc_mode; radio_linear.value = (calc_mode == 1); radio_quad.value = (calc_mode == 2); radio_cubic.value = (calc_mode == 3); // Обновление доступности полей ввода if calc_mode == 1 then edit_c.enable = 'off'; edit_d.enable = 'off'; elseif calc_mode == 2 then edit_c.enable = 'on'; edit_d.enable = 'off'; else edit_c.enable = 'on'; edit_d.enable = 'on'; end endfunction // Основная функция расчёта function perform_calculation() global output_mode calc_mode; // Получение параметров a = evstr(edit_a.string); b = evstr(edit_b.string); c = evstr(edit_c.string); d = evstr(edit_d.string); xmin = evstr(edit_xmin.string); xmax = evstr(edit_xmax.string); // Генерация данных x = linspace(xmin, xmax, 50); // Расчёт в зависимости от режима select calc_mode case 1 // Линейная y = a*x + b; formula = sprintf('y = %.2fx + %.2f', a, b); case 2 // Квадратичная y = a*x.^2 + b*x + c; formula = sprintf('y = %.2fx² + %.2fx + %.2f', a, b, c); case 3 // Кубическая y = a*x.^3 + b*x.^2 + c*x + d; formula = sprintf('y = %.2fx³ + %.2fx² + %.2fx + %.2f', a, b, c, d); end // Вывод результатов в зависимости от режима sca(axes_result); clf(); select output_mode case 1 // Таблица // Создание таблицы данных n_points = 10; // Количество точек для таблицы x_table = linspace(xmin, xmax, n_points); select calc_mode case 1 y_table = a*x_table + b; case 2 y_table = a*x_table.^2 + b*x_table + c; case 3 y_table = a*x_table.^3 + b*x_table.^2 + c*x_table + d; end // Отображение таблицы xtitle('Таблица значений: ' + formula); plot2d([], [], rect=[0,0,1,1], axesflag=0); // Заголовки xstring(0.2, 0.9, 'X'); xstring(0.6, 0.9, 'Y'); // Данные таблицы for i = 1:n_points y_pos = 0.85 - i*0.08; xstring(0.2, y_pos, sprintf('%.2f', x_table(i))); xstring(0.6, y_pos, sprintf('%.4f', y_table(i))); end case 2 // График plot(x, y, 'b-', 'LineWidth', 2); xlabel('X'); ylabel('Y'); title('График функции: ' + formula); xgrid(); case 3 // Текстовый вывод xtitle('Текстовый вывод результатов'); plot2d([], [], rect=[0,0,1,1], axesflag=0); // Вывод информации xstring(0.1, 0.9, 'Функция: ' + formula); xstring(0.1, 0.8, sprintf('Диапазон X: от %.2f до %.2f', xmin, xmax)); xstring(0.1, 0.7, sprintf('Минимальное Y: %.4f', min(y))); xstring(0.1, 0.6, sprintf('Максимальное Y: %.4f', max(y))); xstring(0.1, 0.5, sprintf('Среднее Y: %.4f', mean(y))); // Поиск корней для линейной функции if calc_mode == 1 & a ~= 0 then root = -b/a; xstring(0.1, 0.4, sprintf('Корень уравнения: x = %.4f', root)); end end endfunction // Инициализация update_radio_calc();Эта программа демонстрирует:
-
Использование RadioButton для переключения режимов вывода:
- Таблица значений
- График функции
- Текстовый вывод с характеристиками
-
Использование RadioButton для выбора типа функции:
- Линейная (y = ax + b)
- Квадратичная (y = ax² + bx + c)
- Кубическая (y = ax³ + bx² + cx + d)
-
Динамическое управление интерфейсом:
- Поля ввода активируются/деактивируются в зависимости от выбранной функции
- RadioButton работают как группы (только один может быть выбран)
-
Различные способы отображения результатов:
- Таблица с числовыми значениями
- График функции
- Текстовая информация с характеристиками
Программа позволяет изменять параметры функций и диапазон X, а затем отображать результаты в выбранном формате.
-
- User
у меня есть файлы с решением задач для них нужно создать граф интерфейс. Вот код из этих файлов. Файл 1: // Параметры задачи N = 15; a = -%pi/2; b = %pi/2;
// Создаем массив x значений и вычисляем f(x) x_values = linspace(a, b, N); y_values = ((x_values.^2 + 1).^(1/3)) ./ (0.5 + sqrt(abs(x_values) + 0.5)) .* x_values ./ (1 + sin(x_values).^2);
// Выводим таблицу значений disp(" x f(x)"); disp("------------------"); for i = 1:N printf("%8.4f %8.4f\n", x_values(i), y_values(i)); end
// Строим график с легендой clf(); plot(x_values, y_values, 'r-', 'LineWidth', 2); xlabel('x', 'fontsize', 3); ylabel('f(x)', 'fontsize', 3); title('График функции f(x)', 'fontsize', 3); xgrid();
// Добавляем легенду (после plot, перед show) legend(['f(x)'], 2); Файл 2:// Параметры задачи N = 100; // Количество точек для графика M = 4; // Количество значений для вывода
// Границы отрезка a = -2*%pi; b = 2*%pi;
// 1. Вычисляем M значений функции x_values = linspace(a, b, M); y_values = linspace(a, b, M);
// Вычисляем функцию в точках disp("Вычисленные значения:"); disp(" x y f(x,y)"); disp("----------------------------"); for i = 1:M x = x_values(i); y = y_values(i); f = 5x^2 - 2y^2 + x*y; printf("%7.4f %7.4f %9.4f\n", x, y, f); end
// 2. Строим график по N точкам x_plot = linspace(a, b, N); y_plot = linspace(a, b, N); [X, Y] = ndgrid(x_plot, y_plot); Z = 5X.^2 - 2Y.^2 + X.*Y;
// Создаем 3D график clf(); plot3d(x_plot, y_plot, Z); xlabel("x", "fontsize", 3); ylabel("y", "fontsize", 3); zlabel("f(x,y)", "fontsize", 3); title("График функции f(x,y) = 5x² - 2y² + xy", "fontsize", 3); colorbar(); Файл 3: // Заданная матрица m = [1 2 4 6; 1 -3 7 -9; 21 17 13 11; -6 -4 -2 -1];
// 1. Находим обратную матрицу m_inv = inv(m);
// 2. Проверяем правильность вычислений check = m * m_inv; // Должно получиться единичная матрица
// Выводим результаты disp("Исходная матрица:"); disp(m);
disp("Обратная матрица:"); disp(m_inv);
disp("Проверка (должна быть единичная матрица):"); disp(clean(check)); // clean убирает очень малые числа (ошибки округления)
// 3. Дополнительная проверка через определитель det_m = det(m); disp("Определитель исходной матрицы:"); disp(det_m);
- Assistant
Вот программа с графическим интерфейсом для ваших трех задач с использованием RadioButton:
// Программа с GUI для трех задач clear; clc; close; // Глобальные переменные global task_mode; task_mode = 1; // 1-функция одной переменной, 2-функция двух переменных, 3-обратная матрица // Создание главного окна fig = figure('position', [50 50 900 700], ... 'figure_name', 'Решение задач с графическим интерфейсом', ... 'BackgroundColor', [0.9 0.9 0.9]); // Фрейм для выбора задачи frame_task = uicontrol(fig, 'style', 'frame', ... 'position', [20 550 300 130], ... 'BackgroundColor', [0.85 0.85 0.85]); uicontrol(fig, 'style', 'text', ... 'position', [30 650 280 20], ... 'string', 'Выберите задачу:', ... 'horizontalalignment', 'left', ... 'BackgroundColor', [0.85 0.85 0.85], ... 'fontsize', 12, 'fontweight', 'bold'); // RadioButton для выбора задачи radio_task1 = uicontrol(fig, 'style', 'radiobutton', ... 'position', [40 620 260 20], ... 'string', 'Функция одной переменной', ... 'value', 1, ... 'callback', 'task_mode=1; update_interface();'); radio_task2 = uicontrol(fig, 'style', 'radiobutton', ... 'position', [40 590 260 20], ... 'string', 'Функция двух переменных', ... 'value', 0, ... 'callback', 'task_mode=2; update_interface();'); radio_task3 = uicontrol(fig, 'style', 'radiobutton', ... 'position', [40 560 260 20], ... 'string', 'Обратная матрица', ... 'value', 0, ... 'callback', 'task_mode=3; update_interface();'); // Панель параметров для задачи 1 panel_task1 = uipanel(fig, 'position', [20 200 300 340], ... 'Title', 'Параметры функции f(x)', ... 'BackgroundColor', [0.85 0.85 0.85]); uicontrol(panel_task1, 'style', 'text', ... 'position', [10 290 280 40], ... 'string', 'f(x) = ((x²+1)^(1/3)) / (0.5+√(|x|+0.5)) * x / (1+sin²(x))', ... 'horizontalalignment', 'center', ... 'BackgroundColor', [0.85 0.85 0.85]); uicontrol(panel_task1, 'style', 'text', ... 'position', [10 250 100 20], ... 'string', 'Количество точек N:'); edit1_N = uicontrol(panel_task1, 'style', 'edit', ... 'position', [120 250 60 20], ... 'string', '15'); uicontrol(panel_task1, 'style', 'text', ... 'position', [10 220 100 20], ... 'string', 'Начало отрезка a:'); edit1_a = uicontrol(panel_task1, 'style', 'edit', ... 'position', [120 220 60 20], ... 'string', '-1.5708'); uicontrol(panel_task1, 'style', 'text', ... 'position', [10 190 100 20], ... 'string', 'Конец отрезка b:'); edit1_b = uicontrol(panel_task1, 'style', 'edit', ... 'position', [120 190 60 20], ... 'string', '1.5708'); check1_table = uicontrol(panel_task1, 'style', 'checkbox', ... 'position', [10 150 150 20], ... 'string', 'Показать таблицу', ... 'value', 1); check1_graph = uicontrol(panel_task1, 'style', 'checkbox', ... 'position', [10 120 150 20], ... 'string', 'Показать график', ... 'value', 1); // Панель параметров для задачи 2 panel_task2 = uipanel(fig, 'position', [20 200 300 340], ... 'Title', 'Параметры функции f(x,y)', ... 'BackgroundColor', [0.85 0.85 0.85], ... 'visible', 'off'); uicontrol(panel_task2, 'style', 'text', ... 'position', [10 290 280 30], ... 'string', 'f(x,y) = 5x² - 2y² + xy', ... 'horizontalalignment', 'center', ... 'fontsize', 12, ... 'BackgroundColor', [0.85 0.85 0.85]); uicontrol(panel_task2, 'style', 'text', ... 'position', [10 250 150 20], ... 'string', 'Точек для графика N:'); edit2_N = uicontrol(panel_task2, 'style', 'edit', ... 'position', [170 250 60 20], ... 'string', '50'); uicontrol(panel_task2, 'style', 'text', ... 'position', [10 220 150 20], ... 'string', 'Точек для таблицы M:'); edit2_M = uicontrol(panel_task2, 'style', 'edit', ... 'position', [170 220 60 20], ... 'string', '4'); uicontrol(panel_task2, 'style', 'text', ... 'position', [10 190 150 20], ... 'string', 'Начало отрезка a:'); edit2_a = uicontrol(panel_task2, 'style', 'edit', ... 'position', [170 190 60 20], ... 'string', '-6.2832'); uicontrol(panel_task2, 'style', 'text', ... 'position', [10 160 150 20], ... 'string', 'Конец отрезка b:'); edit2_b = uicontrol(panel_task2, 'style', 'edit', ... 'position', [170 160 60 20], ... 'string', '6.2832'); // Панель параметров для задачи 3 panel_task3 = uipanel(fig, 'position', [20 200 300 340], ... 'Title', 'Параметры матрицы', ... 'BackgroundColor', [0.85 0.85 0.85], ... 'visible', 'off'); uicontrol(panel_task3, 'style', 'text', ... 'position', [10 290 280 20], ... 'string', 'Введите элементы матрицы 4x4:', ... 'horizontalalignment', 'center', ... 'BackgroundColor', [0.85 0.85 0.85]); // Создание полей для ввода матрицы 4x4 edit_matrix = []; for i = 1:4 for j = 1:4 edit_matrix(i,j) = uicontrol(panel_task3, 'style', 'edit', ... 'position', [20 + (j-1)*65, 260 - (i-1)*30, 50, 25], ... 'string', '0'); end end // Заполнение матрицы значениями по умолчанию default_matrix = [1 2 4 6; 1 -3 7 -9; 21 17 13 11; -6 -4 -2 -1]; for i = 1:4 for j = 1:4 set(edit_matrix(i,j), 'string', string(default_matrix(i,j))); end end btn_default = uicontrol(panel_task3, 'style', 'pushbutton', ... 'position', [60 100 180 30], ... 'string', 'Использовать матрицу по умолчанию', ... 'callback', 'set_default_matrix()'); // Кнопка выполнения расчета btn_calc = uicontrol(fig, 'style', 'pushbutton', ... 'position', [75 150 190 40], ... 'string', 'Выполнить расчёт', ... 'fontsize', 12, ... 'callback', 'perform_calculation()'); // Область для вывода результатов axes_result = newaxes(); axes_result.margins = [0.1 0.1 0.1 0.1]; axes_result.axes_bounds = [0.4 0.05 0.55 0.9]; // Текстовая область для вывода text_output = uicontrol(fig, 'style', 'text', ... 'position', [350 20 530 120], ... 'horizontalalignment', 'left', ... 'fontsize', 10, ... 'BackgroundColor', 'white', ... 'visible', 'off'); // Функция обновления интерфейса function update_interface() global task_mode; // Обновление RadioButton radio_task1.value = (task_mode == 1); radio_task2.value = (task_mode == 2); radio_task3.value = (task_mode == 3); // Показываем/скрываем панели panel_task1.visible = (task_mode == 1) ? 'on' : 'off'; panel_task2.visible = (task_mode == 2) ? 'on' : 'off'; panel_task3.visible = (task_mode == 3) ? 'on' : 'off'; // Очистка области результатов sca(axes_result); clf(); text_output.visible = 'off'; endfunction // Функция установки матрицы по умолчанию function set_default_matrix() default_matrix = [1 2 4 6; 1 -3 7 -9; 21 17 13 11; -6 -4 -2 -1]; for i = 1:4 for j = 1:4 set(edit_matrix(i,j), 'string', string(default_matrix(i,j))); end end endfunction // Основная функция расчета function perform_calculation() global task_mode; sca(axes_result); clf(); select task_mode case 1 // Функция одной переменной // Получение параметров N = evstr(edit1_N.string); a = evstr(edit1_a.string); b = evstr(edit1_b.string); show_table = check1_table.value; show_graph = check1_graph.value; // Вычисления x_values = linspace(a, b, N); y_values = ((x_values.^2 + 1).^(1/3)) ./ (0.5 + sqrt(abs(x_values) + 0.5)) .* x_values ./ (1 + sin(x_values).^2); if show_graph then plot(x_values, y_values, 'r-', 'LineWidth', 2); xlabel('x', 'fontsize', 3); ylabel('f(x)', 'fontsize', 3); title('График функции f(x)', 'fontsize', 3); xgrid(); legend(['f(x)'], 2); end if show_table then text_output.visible = 'on'; table_str = "Таблица значений:\n"; table_str = table_str + " x f(x)\n"; table_str = table_str + "------------------------\n"; for i = 1:min(N, 10) // Показываем первые 10 значений table_str = table_str + sprintf("%8.4f %8.4f\n", x_values(i), y_values(i)); end if N > 10 then table_str = table_str + "... (показаны первые 10 из " + string(N) + " значений)"; end text_output.string = table_str; end case 2 // Функция двух переменных // Получение параметров N = evstr(edit2_N.string); M = evstr(edit2_M.string); a = evstr(edit2_a.string); b = evstr(edit2_b.string); // Вычисления для таблицы x_values = linspace(a, b, M); y_values = linspace(a, b, M); // Построение 3D графика x_plot = linspace(a, b, N); y_plot = linspace(a, b, N); [X, Y] = ndgrid(x_plot, y_plot); Z = 5*X.^2 - 2*Y.^2 + X.*Y; plot3d(x_plot, y_plot, Z); xlabel("x", "fontsize", 3); ylabel("y", "fontsize", 3); zlabel("f(x,y)", "fontsize", 3); title("График функции f(x,y) = 5x² - 2y² + xy", "fontsize", 3); colorbar(); // Вывод таблицы значений text_output.visible = 'on'; table_str = "Вычисленные значения:\n"; table_str = table_str + " x y f(x,y)\n"; table_str = table_str + "-----------------------------------\n"; for i = 1:M x = x_values(i); y = y_values(i); f = 5*x^2 - 2*y^2 + x*y; table_str = table_str + sprintf("%7.4f %7.4f %9.4f\n", x, y, f); end text_output.string = table_str; case 3 // Обратная матрица // Получение матрицы из полей ввода m = []; for i = 1:4 for j = 1:4 m(i,j) = evstr(get(edit_matrix(i,j), 'string')); end end // Проверка определителя det_m = det(m); if abs(det_m) < 1e-10 then text_output.visible = 'on'; text_output.string = "ОШИБКА: Матрица вырожденная (определитель ≈ 0).\nОбратная матрица не существует!"; return; end // Вычисление обратной матрицы m_inv = inv(m); // Проверка check = m * m_inv; // Визуализация матриц subplot(2,2,1); Matplot(m); xtitle("Исходная матрица"); subplot(2,2,2); Matplot(m_inv); xtitle("Обратная матрица"); subplot(2,2,3); Matplot(clean(check)); xtitle("Проверка (M * M⁻¹)"); // Текстовый вывод text_output.visible = 'on'; output_str = sprintf("Определитель исходной матрицы: %.6f\n", det_m); output_str = output_str + "\nМаксимальная ошибка в единичной матрице: "; output_str = output_str + sprintf("%.2e", max(abs(check - eye(4,4)))); text_output.string = output_str; end endfunctionЭта программа создает единый интерфейс для всех трех задач с следующими возможностями:
- RadioButton для выбора задачи - переключение между тремя задачами
- Динамические панели параметров - для каждой задачи своя панель с соответствующими полями ввода
- Универсальная область вывода - адаптируется под тип задачи (графики 2D/3D, таблицы)
- Сохранение оригинальной логики - все вычисления выполняются так же, как в исходных файлах
Особенности реализации:
- Для задачи 1: можно выбрать отображение таблицы и/или графика
- Для задачи 2: автоматически строится 3D график и выводится таблица значений
- Для задачи 3: визуализация матриц и проверка корректности вычислений
- User
в первом и во втором случае должен быть еще выбор чтобы выводилась таблица со значениями x и y
- Assistant
Вот обновленная версия программы с улучшенным выводом таблиц для первой и второй задачи:
// Программа с GUI для трех задач clear; clc; close; // Глобальные переменные global task_mode; task_mode = 1; // 1-функция одной переменной, 2-функция двух переменных, 3-обратная матрица // Создание главного окна fig = figure('position', [50 50 900 700], ... 'figure_name', 'Решение задач с графическим интерфейсом', ... 'BackgroundColor', [0.9 0.9 0.9]); // Фрейм для выбора задачи frame_task = uicontrol(fig, 'style', 'frame', ... 'position', [20 550 300 130], ... 'BackgroundColor', [0.85 0.85 0.85]); uicontrol(fig, 'style', 'text', ... 'position', [30 650 280 20], ... 'string', 'Выберите задачу:', ... 'horizontalalignment', 'left', ... 'BackgroundColor', [0.85 0.85 0.85], ... 'fontsize', 12, 'fontweight', 'bold'); // RadioButton для выбора задачи radio_task1 = uicontrol(fig, 'style', 'radiobutton', ... 'position', [40 620 260 20], ... 'string', 'Функция одной переменной', ... 'value', 1, ... 'callback', 'task_mode=1; update_interface();'); radio_task2 = uicontrol(fig, 'style', 'radiobutton', ... 'position', [40 590 260 20], ... 'string', 'Функция двух переменных', ... 'value', 0, ... 'callback', 'task_mode=2; update_interface();'); radio_task3 = uicontrol(fig, 'style', 'radiobutton', ... 'position', [40 560 260 20], ... 'string', 'Обратная матрица', ... 'value', 0, ... 'callback', 'task_mode=3; update_interface();'); // Панель параметров для задачи 1 panel_task1 = uipanel(fig, 'position', [20 200 300 340], ... 'Title', 'Параметры функции f(x)', ... 'BackgroundColor', [0.85 0.85 0.85]); uicontrol(panel_task1, 'style', 'text', ... 'position', [10 290 280 40], ... 'string', 'f(x) = ((x²+1)^(1/3)) / (0.5+√(|x|+0.5)) * x / (1+sin²(x))', ... 'horizontalalignment', 'center', ... 'BackgroundColor', [0.85 0.85 0.85]); uicontrol(panel_task1, 'style', 'text', ... 'position', [10 250 100 20], ... 'string', 'Количество точек N:'); edit1_N = uicontrol(panel_task1, 'style', 'edit', ... 'position', [120 250 60 20], ... 'string', '15'); uicontrol(panel_task1, 'style', 'text', ... 'position', [10 220 100 20], ... 'string', 'Начало отрезка a:'); edit1_a = uicontrol(panel_task1, 'style', 'edit', ... 'position', [120 220 60 20], ... 'string', '-1.5708'); uicontrol(panel_task1, 'style', 'text', ... 'position', [10 190 100 20], ... 'string', 'Конец отрезка b:'); edit1_b = uicontrol(panel_task1, 'style', 'edit', ... 'position', [120 190 60 20], ... 'string', '1.5708'); // Фрейм для режима вывода задачи 1 frame1_output = uicontrol(panel_task1, 'style', 'frame', ... 'position', [10 70 280 70], ... 'BackgroundColor', [0.8 0.8 0.8]); uicontrol(panel_task1, 'style', 'text', ... 'position', [20 110 100 20], ... 'string', 'Режим вывода:', ... 'BackgroundColor', [0.8 0.8 0.8]); radio1_table = uicontrol(panel_task1, 'style', 'radiobutton', ... 'position', [130 110 100 20], ... 'string', 'Таблица', ... 'value', 1, ... 'BackgroundColor', [0.8 0.8 0.8]); radio1_graph = uicontrol(panel_task1, 'style', 'radiobutton', ... 'position', [130 80 100 20], ... 'string', 'График', ... 'value', 0, ... 'BackgroundColor', [0.8 0.8 0.8]); // Панель параметров для задачи 2 panel_task2 = uipanel(fig, 'position', [20 200 300 340], ... 'Title', 'Параметры функции f(x,y)', ... 'BackgroundColor', [0.85 0.85 0.85], ... 'visible', 'off'); uicontrol(panel_task2, 'style', 'text', ... 'position', [10 290 280 30], ... 'string', 'f(x,y) = 5x² - 2y² + xy', ... 'horizontalalignment', 'center', ... 'fontsize', 12, ... 'BackgroundColor', [0.85 0.85 0.85]); uicontrol(panel_task2, 'style', 'text', ... 'position', [10 250 150 20], ... 'string', 'Точек для графика N:'); edit2_N = uicontrol(panel_task2, 'style', 'edit', ... 'position', [170 250 60 20], ... 'string', '50'); uicontrol(panel_task2, 'style', 'text', ... 'position', [10 220 150 20], ... 'string', 'Точек для таблицы M:'); edit2_M = uicontrol(panel_task2, 'style', 'edit', ... 'position', [170 220 60 20], ... 'string', '4'); uicontrol(panel_task2, 'style', 'text', ... 'position', [10 190 150 20], ... 'string', 'Начало отрезка a:'); edit2_a = uicontrol(panel_task2, 'style', 'edit', ... 'position', [170 190 60 20], ... 'string', '-6.2832'); uicontrol(panel_task2, 'style', 'text', ... 'position', [10 160 150 20], ... 'string', 'Конец отрезка b:'); edit2_b = uicontrol(panel_task2, 'style', 'edit', ... 'position', [170 160 60 20], ... 'string', '6.2832'); // Фрейм для режима вывода задачи 2 frame2_output = uicontrol(panel_task2, 'style', 'frame', ... 'position', [10 70 280 70], ... 'BackgroundColor', [0.8 0.8 0.8]); uicontrol(panel_task2, 'style', 'text', ... 'position', [20 110 100 20], ... 'string', 'Режим вывода:', ... 'BackgroundColor', [0.8 0.8 0.8]); radio2_table = uicontrol(panel_task2, 'style', 'radiobutton', ... 'position', [130 110 100 20], ... 'string', 'Таблица', ... 'value', 1, ... 'BackgroundColor', [0.8 0.8 0.8]); radio2_graph = uicontrol(panel_task2, 'style', 'radiobutton', ... 'position', [130 80 100 20], ... 'string', '3D График', ... 'value', 0, ... 'BackgroundColor', [0.8 0.8 0.8]); // Панель параметров для задачи 3 panel_task3 = uipanel(fig, 'position', [20 200 300 340], ... 'Title', 'Параметры матрицы', ... 'BackgroundColor', [0.85 0.85 0.85], ... 'visible', 'off'); uicontrol(panel_task3, 'style', 'text', ... 'position', [10 290 280 20], ... 'string', 'Введите элементы матрицы 4x4:', ... 'horizontalalignment', 'center', ... 'BackgroundColor', [0.85 0.85 0.85]); // Создание полей для ввода матрицы 4x4 edit_matrix = []; for i = 1:4 for j = 1:4 edit_matrix(i,j) = uicontrol(panel_task3, 'style', 'edit', ... 'position', [20 + (j-1)*65, 260 - (i-1)*30, 50, 25], ... 'string', '0'); end end // Заполнение матрицы значениями по умолчанию default_matrix = [1 2 4 6; 1 -3 7 -9; 21 17 13 11; -6 -4 -2 -1]; for i = 1:4 for j = 1:4 set(edit_matrix(i,j), 'string', string(default_matrix(i,j))); end end btn_default = uicontrol(panel_task3, 'style', 'pushbutton', ... 'position', [60 100 180 30], ... 'string', 'Использовать матрицу по умолчанию', ... 'callback', 'set_default_matrix()'); // Кнопка выполнения расчета btn_calc = uicontrol(fig, 'style', 'pushbutton', ... 'position', [75 150 190 40], ... 'string', 'Выполнить расчёт', ... 'fontsize', 12, ... 'callback', 'perform_calculation()'); // Область для вывода результатов axes_result = newaxes(); axes_result.margins = [0.1 0.1 0.1 0.1]; axes_result.axes_bounds = [0.4 0.05 0.55 0.9]; // Listbox для вывода таблицы list_table = uicontrol(fig, 'style', 'listbox', ... 'position', [350 50 530 600], ... 'fontname', 'monospace', ... 'fontsize', 10, ... 'visible', 'off'); // Функция обновления интерфейса function update_interface() global task_mode; // Обновление RadioButton radio_task1.value = (task_mode == 1); radio_task2.value = (task_mode == 2); radio_task3.value = (task_mode == 3); // Показываем/скрываем панели panel_task1.visible = (task_mode == 1) ? 'on' : 'off'; panel_task2.visible = (task_mode == 2) ? 'on' : 'off'; panel_task3.visible = (task_mode == 3) ? 'on' : 'off'; // Очистка области результатов sca(axes_result); clf(); list_table.visible = 'off'; endfunction // Функция установки матрицы по умолчанию function set_default_matrix() default_matrix = [1 2 4 6; 1 -3 7 -9; 21 17 13 11; -6 -4 -2 -1]; for i = 1:4 for j = 1:4 set(edit_matrix(i,j), 'string', string(default_matrix(i,j))); end end endfunction // Обработчики для RadioButton режима вывода radio1_table.callback = 'radio1_table.value=1; radio1_graph.value=0;'; radio1_graph.callback = 'radio1_table.value=0; radio1_graph.value=1;'; radio2_table.callback = 'radio2_table.value=1; radio2_graph.value=0;'; radio2_graph.callback = 'radio2_table.value=0; radio2_graph.value=1;'; // Основная функция расчета function perform_calculation() global task_mode; sca(axes_result); clf(); list_table.visible = 'off'; select task_mode case 1 // Функция одной переменной // Получение параметров N = evstr(edit1_N.string); a = evstr(edit1_a.string); b = evstr(edit1_b.string); show_table = radio1_table.value; show_graph = radio1_graph.value; // Вычисления x_values = linspace(a, b, N); y_values = ((x_values.^2 + 1).^(1/3)) ./ (0.5 + sqrt(abs(x_values) + 0.5)) .* x_values ./ (1 + sin(x_values).^2); if show_graph then axes_result.visible = 'on'; plot(x_values, y_values, 'r-', 'LineWidth', 2); xlabel('x', 'fontsize', 3); ylabel('f(x)', 'fontsize', 3); title('График функции f(x)', 'fontsize', 3); xgrid(); legend(['f(x)'], 2); else axes_result.visible = 'off'; end if show_table then list_table.visible = 'on'; table_data = []; table_data($+1) = " Таблица значений функции f(x)"; table_data($+1) = " ================================"; table_data($+1) = sprintf(" %12s %12s", "x", "f(x)"); table_data($+1) = " --------------------------------"; for i = 1:N table_data($+1) = sprintf(" %12.6f %12.6f", x_values(i), y_values(i)); end list_table.string = table_data; end case 2 // Функция двух переменных // Получение параметров N = evstr(edit2_N.string); M = evstr(edit2_M.string); a = evstr(edit2_a.string); b = evstr(edit2_b.string); show_table = radio2_table.value; show_graph = radio2_graph.value; if show_graph then axes_result.visible = 'on'; // Построение 3D графика x_plot = linspace(a, b, N); y_plot = linspace(a, b, N); [X, Y] = ndgrid(x_plot, y_plot); Z = 5*X.^2 - 2*Y.^2 + X.*Y; plot3d(x_plot, y_plot, Z); xlabel("x", "fontsize", 3); ylabel("y", "fontsize", 3); zlabel("f(x,y)", "fontsize", 3); title("График функции f(x,y) = 5x² - 2y² + xy", "fontsize", 3); colorbar(); else axes_result.visible = 'off'; end if show_table then list_table.visible = 'on'; // Вычисления для таблицы x_values = linspace(a, b, M); y_values = linspace(a, b, M); table_data = []; table_data($+1) = " Таблица значений функции f(x,y) = 5x² - 2y² + xy"; table_data($+1) = " ================================================="; table_data($+1) = sprintf(" %10s %10s %12s", "x", "y", "f(x,y)"); table_data($+1) = " -------------------------------------------------"; for i = 1:M x = x_values(i); y = y_values(i); f = 5*x^2 - 2*y^2 + x*y; table_data($+1) = sprintf(" %10.4f %10.4f %12.4f", x, y, f); end list_table.string = table_data; end case 3 // Обратная матрица axes_result.visible = 'on'; // Получение матрицы из полей ввода m = []; for i = 1:4 for j = 1:4 m(i,j) = evstr(get(edit_matrix(i,j), 'string')); end end // Проверка определителя det_m = det(m); if abs(det_m) < 1e-10 then list_table.visible = 'on'; list_table.string = ["ОШИБКА: Матрица вырожденная (определитель ≈ 0)."; ... "Обратная матрица не существует!"]; return; end // Вычисление обратной матрицы m_inv = inv(m); // Проверка check = m * m_inv; // Визуализация матриц subplot(2,2,1); Matplot(m); xtitle("Исходная матрица"); subplot(2,2,2); Matplot(m_inv); xtitle("Обратная матрица"); subplot(2,2,3); Matplot(clean(check)); xtitle("Проверка (M * M⁻¹)"); // Текстовый вывод результатов subplot(2,2,4); plot2d([], [], rect=[0,0,1,1], axesflag=0); xstring(0.1, 0.8, sprintf("Определитель: %.6f", det_m)); xstring(0.1, 0.6, "Максимальная ошибка"); xstring(0.1, 0.5, "в единичной матрице:"); xstring(0.1, 0.3, sprintf("%.2e", max(abs(check - eye(4,4))))); end endfunctionОсновные изменения и улучшения:
-
RadioButton для режима вывода в задаче 1:
- Переключение между таблицей и графиком
- Таблица отображается в отдельном listbox с форматированным выводом
-
RadioButton для режима вывода в задаче 2:
- Переключение между таблицей и 3D графиком
- Таблица показывает значения x, y и f(x,y)
-
Улучшенный вывод таблиц:
- Использование listbox для лучшего отображения табличных данных
- Форматированный вывод с заголовками и разделителями
- Моноширинный шрифт для выравнивания столбцов
-
Динамическое управление видимостью:
- График и таблица скрываются/показываются в зависимости от выбранного режима
- Каждая задача имеет свои независимые настройки вывода
Теперь пользователь может выбирать для каждой задачи, хочет ли он видеть таблицу значений или график (или 3D график для второй задачи).
-
- User
можешь убрать одновременный выбор нескольких задач
- Assistant
Вот исправленная версия программы с правильной группировкой RadioButton:
// Программа с GUI для трех задач clear; clc; close; // Глобальные переменные global task_mode output_mode1 output_mode2; task_mode = 1; // 1-функция одной переменной, 2-функция двух переменных, 3-обратная матрица output_mode1 = 1; // 1-таблица, 2-график для задачи 1 output_mode2 = 1; // 1-таблица, 2-график для задачи 2 // Создание главного окна fig = figure('position', [50 50 900 700], ... 'figure_name', 'Решение задач с графическим интерфейсом', ... 'BackgroundColor', [0.9 0.9 0.9]); // Фрейм для выбора задачи frame_task = uicontrol(fig, 'style', 'frame', ... 'position', [20 550 300 130], ... 'BackgroundColor', [0.85 0.85 0.85]); uicontrol(fig, 'style', 'text', ... 'position', [30 650 280 20], ... 'string', 'Выберите задачу:', ... 'horizontalalignment', 'left', ... 'BackgroundColor', [0.85 0.85 0.85], ... 'fontsize', 12, 'fontweight', 'bold'); // RadioButton для выбора задачи - все в одном родителе для автоматической группировки radio_task1 = uicontrol(fig, 'style', 'radiobutton', ... 'position', [40 620 260 20], ... 'string', 'Функция одной переменной', ... 'value', 1, ... 'callback', 'select_task(1)'); radio_task2 = uicontrol(fig, 'style', 'radiobutton', ... 'position', [40 590 260 20], ... 'string', 'Функция двух переменных', ... 'value', 0, ... 'callback', 'select_task(2)'); radio_task3 = uicontrol(fig, 'style', 'radiobutton', ... 'position', [40 560 260 20], ... 'string', 'Обратная матрица', ... 'value', 0, ... 'callback', 'select_task(3)'); // Панель параметров для задачи 1 panel_task1 = uipanel(fig, 'position', [20 200 300 340], ... 'Title', 'Параметры функции f(x)', ... 'BackgroundColor', [0.85 0.85 0.85]); uicontrol(panel_task1, 'style', 'text', ... 'position', [10 290 280 40], ... 'string', 'f(x) = ((x²+1)^(1/3)) / (0.5+√(|x|+0.5)) * x / (1+sin²(x))', ... 'horizontalalignment', 'center', ... 'BackgroundColor', [0.85 0.85 0.85]); uicontrol(panel_task1, 'style', 'text', ... 'position', [10 250 100 20], ... 'string', 'Количество точек N:'); edit1_N = uicontrol(panel_task1, 'style', 'edit', ... 'position', [120 250 60 20], ... 'string', '15'); uicontrol(panel_task1, 'style', 'text', ... 'position', [10 220 100 20], ... 'string', 'Начало отрезка a:'); edit1_a = uicontrol(panel_task1, 'style', 'edit', ... 'position', [120 220 60 20], ... 'string', '-1.5708'); uicontrol(panel_task1, 'style', 'text', ... 'position', [10 190 100 20], ... 'string', 'Конец отрезка b:'); edit1_b = uicontrol(panel_task1, 'style', 'edit', ... 'position', [120 190 60 20], ... 'string', '1.5708'); // Фрейм для режима вывода задачи 1 frame1_output = uicontrol(panel_task1, 'style', 'frame', ... 'position', [10 70 280 70], ... 'BackgroundColor', [0.8 0.8 0.8]); uicontrol(panel_task1, 'style', 'text', ... 'position', [20 110 100 20], ... 'string', 'Режим вывода:', ... 'BackgroundColor', [0.8 0.8 0.8]); radio1_table = uicontrol(panel_task1, 'style', 'radiobutton', ... 'position', [130 110 100 20], ... 'string', 'Таблица', ... 'value', 1, ... 'BackgroundColor', [0.8 0.8 0.8], ... 'callback', 'select_output1(1)'); radio1_graph = uicontrol(panel_task1, 'style', 'radiobutton', ... 'position', [130 80 100 20], ... 'string', 'График', ... 'value', 0, ... 'BackgroundColor', [0.8 0.8 0.8], ... 'callback', 'select_output1(2)'); // Панель параметров для задачи 2 panel_task2 = uipanel(fig, 'position', [20 200 300 340], ... 'Title', 'Параметры функции f(x,y)', ... 'BackgroundColor', [0.85 0.85 0.85], ... 'visible', 'off'); uicontrol(panel_task2, 'style', 'text', ... 'position', [10 290 280 30], ... 'string', 'f(x,y) = 5x² - 2y² + xy', ... 'horizontalalignment', 'center', ... 'fontsize', 12, ... 'BackgroundColor', [0.85 0.85 0.85]); uicontrol(panel_task2, 'style', 'text', ... 'position', [10 250 150 20], ... 'string', 'Точек для графика N:'); edit2_N = uicontrol(panel_task2, 'style', 'edit', ... 'position', [170 250 60 20], ... 'string', '50'); uicontrol(panel_task2, 'style', 'text', ... 'position', [10 220 150 20], ... 'string', 'Точек для таблицы M:'); edit2_M = uicontrol(panel_task2, 'style', 'edit', ... 'position', [170 220 60 20], ... 'string', '4'); uicontrol(panel_task2, 'style', 'text', ... 'position', [10 190 150 20], ... 'string', 'Начало отрезка a:'); edit2_a = uicontrol(panel_task2, 'style', 'edit', ... 'position', [170 190 60 20], ... 'string', '-6.2832'); uicontrol(panel_task2, 'style', 'text', ... 'position', [10 160 150 20], ... 'string', 'Конец отрезка b:'); edit2_b = uicontrol(panel_task2, 'style', 'edit', ... 'position', [170 160 60 20], ... 'string', '6.2832'); // Фрейм для режима вывода задачи 2 frame2_output = uicontrol(panel_task2, 'style', 'frame', ... 'position', [10 70 280 70], ... 'BackgroundColor', [0.8 0.8 0.8]); uicontrol(panel_task2, 'style', 'text', ... 'position', [20 110 100 20], ... 'string', 'Режим вывода:', ... 'BackgroundColor', [0.8 0.8 0.8]); radio2_table = uicontrol(panel_task2, 'style', 'radiobutton', ... 'position', [130 110 100 20], ... 'string', 'Таблица', ... 'value', 1, ... 'BackgroundColor', [0.8 0.8 0.8], ... 'callback', 'select_output2(1)'); radio2_graph = uicontrol(panel_task2, 'style', 'radiobutton', ... 'position', [130 80 100 20], ... 'string', '3D График', ... 'value', 0, ... 'BackgroundColor', [0.8 0.8 0.8], ... 'callback', 'select_output2(2)'); // Панель параметров для задачи 3 panel_task3 = uipanel(fig, 'position', [20 200 300 340], ... 'Title', 'Параметры матрицы', ... 'BackgroundColor', [0.85 0.85 0.85], ... 'visible', 'off'); uicontrol(panel_task3, 'style', 'text', ... 'position', [10 290 280 20], ... 'string', 'Введите элементы матрицы 4x4:', ... 'horizontalalignment', 'center', ... 'BackgroundColor', [0.85 0.85 0.85]); // Создание полей для ввода матрицы 4x4 edit_matrix = []; for i = 1:4 for j = 1:4 edit_matrix(i,j) = uicontrol(panel_task3, 'style', 'edit', ... 'position', [20 + (j-1)*65, 260 - (i-1)*30, 50, 25], ... 'string', '0'); end end // Заполнение матрицы значениями по умолчанию default_matrix = [1 2 4 6; 1 -3 7 -9; 21 17 13 11; -6 -4 -2 -1]; for i = 1:4 for j = 1:4 set(edit_matrix(i,j), 'string', string(default_matrix(i,j))); end end btn_default = uicontrol(panel_task3, 'style', 'pushbutton', ... 'position', [60 100 180 30], ... 'string', 'Использовать матрицу по умолчанию', ... 'callback', 'set_default_matrix()'); // Кнопка выполнения расчета btn_calc = uicontrol(fig, 'style', 'pushbutton', ... 'position', [75 150 190 40], ... 'string', 'Выполнить расчёт', ... 'fontsize', 12, ... 'callback', 'perform_calculation()'); // Область для вывода результатов axes_result = newaxes(); axes_result.margins = [0.1 0.1 0.1 0.1]; axes_result.axes_bounds = [0.4 0.05 0.55 0.9]; // Listbox для вывода таблицы list_table = uicontrol(fig, 'style', 'listbox', ... 'position', [350 50 530 600], ... 'fontname', 'monospace', ... 'fontsize', 10, ... 'visible', 'off'); // Функция выбора задачи function select_task(task_num) global task_mode; task_mode = task_num; // Обновляем состояние RadioButton radio_task1.value = (task_num == 1); radio_task2.value = (task_num == 2); radio_task3.value = (task_num == 3); // Показываем/скрываем панели panel_task1.visible = (task_num == 1) ? 'on' : 'off'; panel_task2.visible = (task_num == 2) ? 'on' : 'off'; panel_task3.visible = (task_num == 3) ? 'on' : 'off'; // Очистка области результатов sca(axes_result); clf(); list_table.visible = 'off'; endfunction // Функции выбора режима вывода function select_output1(mode) global output_mode1; output_mode1 = mode; radio1_table.value = (mode == 1); radio1_graph.value = (mode == 2); endfunction function select_output2(mode) global output_mode2; output_mode2 = mode; radio2_table.value = (mode == 1); radio2_graph.value = (mode == 2); endfunction // Функция установки матрицы по умолчанию function set_default_matrix() default_matrix = [1 2 4 6; 1 -3 7 -9; 21 17 13 11; -6 -4 -2 -1]; for i = 1:4 for j = 1:4 set(edit_matrix(i,j), 'string', string(default_matrix(i,j))); end end endfunction // Основная функция расчета function perform_calculation() global task_mode output_mode1 output_mode2; sca(axes_result); clf(); list_table.visible = 'off'; select task_mode case 1 // Функция одной переменной // Получение параметров N = evstr(edit1_N.string); a = evstr(edit1_a.string); b = evstr(edit1_b.string); // Вычисления x_values = linspace(a, b, N); y_values = ((x_values.^2 + 1).^(1/3)) ./ (0.5 + sqrt(abs(x_values) + 0.5)) .* x_values ./ (1 + sin(x_values).^2); if output_mode1 == 2 then // График axes_result.visible = 'on'; plot(x_values, y_values, 'r-', 'LineWidth', 2); xlabel('x', 'fontsize', 3); ylabel('f(x)', 'fontsize', 3); title('График функции f(x)', 'fontsize', 3); xgrid(); legend(['f(x)'], 2); else axes_result.visible = 'off'; end if output_mode1 == 1 then // Таблица list_table.visible = 'on'; table_data = []; table_data($+1) = " Таблица значений функции f(x)"; table_data($+1) = " ================================"; table_data($+1) = sprintf(" %12s %12s", "x", "f(x)"); table_data($+1) = " --------------------------------"; for i = 1:N table_data($+1) = sprintf(" %12.6f %12.6f", x_values(i), y_values(i)); end list_table.string = table_data; end case 2 // Функция двух переменных // Получение параметров N = evstr(edit2_N.string); M = evstr(edit2_M.string); a = evstr(edit2_a.string); b = evstr(edit2_b.string); if output_mode2 == 2 then // 3D График axes_result.visible = 'on'; // Построение 3D графика x_plot = linspace(a, b, N); y_plot = linspace(a, b, N); [X, Y] = ndgrid(x_plot, y_plot); Z = 5*X.^2 - 2*Y.^2 + X.*Y; plot3d(x_plot, y_plot, Z); xlabel("x", "fontsize", 3); ylabel("y", "fontsize", 3); zlabel("f(x,y)", "fontsize", 3); title("График функции f(x,y) = 5x² - 2y² + xy", "fontsize", 3); colorbar(); else axes_result.visible = 'off'; end if output_mode2 == 1 then // Таблица list_table.visible = 'on'; // Вычисления для таблицы x_values = linspace(a, b, M); y_values = linspace(a, b, M); table_data = []; table_data($+1) = " Таблица значений функции f(x,y) = 5x² - 2y² + xy"; table_data($+1) = " ================================================="; table_data($+1) = sprintf(" %10s %10s %12s", "x", "y", "f(x,y)"); table_data($+1) = " -------------------------------------------------"; for i = 1:M x = x_values(i); y = y_values(i); f = 5*x^2 - 2*y^2 + x*y; table_data($+1) = sprintf(" %10.4f %10.4f %12.4f", x, y, f); end list_table.string = table_data; end case 3 // Обратная матрица axes_result.visible = 'on'; // Получение матрицы из полей ввода m = []; for i = 1:4 for j = 1:4 m(i,j) = evstr(get(edit_matrix(i,j), 'string')); end end // Проверка определителя det_m = det(m); if abs(det_m) < 1e-10 then list_table.visible = 'on'; list_table.string = ["ОШИБКА: Матрица вырожденная (определитель ≈ 0)."; ... "Обратная матрица не существует!"]; return; end // Вычисление обратной матрицы m_inv = inv(m); // Проверка check = m * m_inv; // Визуализация матриц subplot(2,2,1); Matplot(m); xtitle("Исходная матрица"); subplot(2,2,2); Matplot(m_inv); xtitle("Обратная матрица"); subplot(2,2,3); Matplot(clean(check)); xtitle("Проверка (M * M⁻¹)"); // Текстовый вывод результатов subplot(2,2,4); plot2d([], [], rect=[0,0,1,1], axesflag=0); xstring(0.1, 0.8, sprintf("Определитель: %.6f", det_m)); xstring(0.1, 0.6, "Максимальная ошибка"); xstring(0.1, 0.5, "в единичной матрице:"); xstring(0.1, 0.3, sprintf("%.2e", max(abs(check - eye(4,4))))); end endfunctionОсновные изменения:
-
Явные функции управления RadioButton:
select_task()- управляет выбором задачиselect_output1()иselect_output2()- управляют режимом вывода
-
Правильная группировка:
- Все RadioButton для выбора задачи имеют один родитель (fig)
- RadioButton для режима вывода группируются внутри своих панелей
-
Глобальные переменные:
- Отдельные переменные для хранения режима вывода каждой задачи
- Состояние сохраняется при переключении между задачами
Теперь невозможно выбрать несколько задач одновременно, и RadioButton работают как правильные взаимоисключающие группы.
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.