许可优化
许可优化
产品
产品
解决方案
解决方案
服务支持
服务支持
关于
关于
软件库
当前位置:服务支持 >  软件文章 >  零成本matlab加本地AI大模型自适应改代码

零成本matlab加本地AI大模型自适应改代码

阅读数 3
点赞 0
article_banner


视频配套代码

(有手就行)零成本matlab+本地AI调代码​

1)无需api,零成本直接运行本地模型

2)无需第三方界面,直接在matlab软件上面调,实现编程闭合

3)支持根据报错自己修改代码,拒绝输出不可用的错误代码

4)支持直接测试运行再保存的逻辑,不会产生过多垃圾文件

另外,想直接调用优秀付费的网络大模型,可以参考这个视频,deepseek+matlab编程及自动修改代码!无需额外下载任何编辑器!零帧入门ai编程!小白福音!​调用deepseek实现更快更好地编程功能!

零成本matlab加本地AI

disp('=== AI代码生成器 (Ollama 本地模型 gemma3:1b) ===');

disp(' 多轮对话模式:可连续提问,AI 会记住上下文');

disp(' 指令: /run(运行代码) /save(保存代码) /clear(清空记忆) exit/q(退出)');

disp('');

model_name = 'gemma3:1b';

system_prompt = '你是一个MATLAB编程专家。请根据用户的编程要求,生成完整、可运行的MATLAB脚本代码。代码必须是脚本形式(script),不要定义函数(function),所有代码都应该可以直接在命令窗口运行。代码用 ```matlab ... ``` 包裹。代码前后可以有简短的文字说明。';

% 初始化对话历史(cell 数组,每个元素是 struct: .role, .content)

messages = {};

messages{1}.role = 'system';

messages{1}.content = system_prompt;

last_code = '';

while true

user_input = input('You: ', 's');

if isempty(user_input)

continue;

end

% 退出指令

if strcmpi(user_input, 'exit') || strcmpi(user_input, 'quit') || strcmpi(user_input, 'q')

disp('对话结束,再见!');

break;

end

% 运行代码

if strcmpi(user_input, '/run')

if isempty(last_code)

disp('没有可运行的代码。');

else

run_code_and_fix(last_code);

end

continue;

end

% 保存代码

if strcmpi(user_input, '/save')

if isempty(last_code)

disp('没有可保存的代码。');

else

save_code(last_code);

end

continue;

end

% 清空对话历史

if strcmpi(user_input, '/clear')

messages = {};

messages{1}.role = 'system';

messages{1}.content = system_prompt;

last_code = '';

disp('对话历史已清空,上下文已重置。');

disp('');

continue;

end

% 帮助

if strcmpi(user_input, '/help')

disp('--- 可用指令 ---');

disp(' /run 运行最近生成的代码');

disp(' /save 保存最近生成的代码');

disp(' /clear 清空对话记忆(重置上下文)');

disp(' exit / q 退出对话');

disp('----------------');

continue;

end

% ---- 发送请求 ----

% 添加用户消息到历史

msg_idx = length(messages) + 1;

messages{msg_idx}.role = 'user';

messages{msg_idx}.content = user_input;

disp('');

fprintf('AI: ');

[response_text, messages, success] = call_ollama_api(model_name, messages);

if ~success

% 移除失败的用户消息

messages = messages(1:end-1);

disp('');

continue;

end

% 显示完整回应

disp(response_text);

disp('');

% 提取代码块

extracted_code = extract_code_block(response_text);

if ~isempty(extracted_code)

last_code = extracted_code;

disp('⚡ 检测到代码块,输入 /run 运行, /save 保存');

end

disp('----------------------------------------');

end

% ==================== API 调用 ====================

function [response_text, messages, success] = call_ollama_api(model_name, messages)

url = 'http://localhost:11434/api/chat';

% 从 message 历史动态构建 JSON

json_data = build_messages_json(model_name, messages);

headers = {

'Content-Type', 'application/json'

};

try

options = weboptions('HeaderFields', headers, 'MediaType', 'application/json', 'Timeout', 180);

response = webwrite(url, json_data, options);

response_text = response.message.content;

response_text = strtrim(response_text);

% 添加 AI 回复到历史

msg_idx = length(messages) + 1;

messages{msg_idx}.role = 'assistant';

messages{msg_idx}.content = response_text;

success = true;

catch ME

disp(['Ollama API 调用失败: ', ME.message]);

disp(' 可能原因:');

disp(' 1) Ollama 应用程序未启动');

disp(' 2) 模型 gemma3:1b 未下载,执行: ollama pull gemma3:1b');

disp(' 3) 端口 11434 被占用');

response_text = '';

success = false;

end

end

% ==================== JSON 构造 ====================

function json_data = build_messages_json(model_name, messages)

msg_parts = {};

for i = 1:length(messages)

role = messages{i}.role;

content_esc = escape_json(messages{i}.content);

msg_parts{i} = sprintf('{"role":"%s","content":"%s"}', role, content_esc);

end

msg_str = strjoin(msg_parts, ',');

json_data = sprintf(['{"model":"%s","messages":[%s],', ...

'"stream":false,"options":{"temperature":0.3}}'], model_name, msg_str);

end

% ==================== JSON 转义 ====================

function escaped = escape_json(str)

escaped = strrep(str, '\', '\\');

escaped = strrep(escaped, '"', '\"');

escaped = strrep(escaped, char(10), '\n');

escaped = strrep(escaped, char(13), '\r');

end

% ==================== 代码块提取 ====================

function code = extract_code_block(text)

code = '';

start_tag = '```matlab';

start_pos = strfind(text, start_tag);

if isempty(start_pos)

start_tag = '```m';

start_pos = strfind(text, start_tag);

end

if isempty(start_pos)

start_tag = char(96) + char(96) + char(96); % ```

start_pos = strfind(text, start_tag);

end

if isempty(start_pos)

return;

end

start_pos = start_pos(1) + length(start_tag);

% 跳过可能的换行

while start_pos <= length(text) && (text(start_pos) == char(10) || text(start_pos) == char(13))

start_pos = start_pos + 1;

end

end_pos = strfind(text(start_pos:end), '```');

if isempty(end_pos)

code = strtrim(text(start_pos:end));

else

code = strtrim(text(start_pos : start_pos + end_pos(1) - 2));

end

end

% ==================== 运行并修复 ====================

function run_code_and_fix(code)

max_attempts = 30;

attempt = 1;

success_val = false;

current_code = code;

if contains(current_code, 'function ')

disp('检测到函数定义代码,正在转换为脚本形式...');

current_code = convert_function_to_script(current_code);

disp('转换后的脚本代码:');

disp('----------------------------------------');

disp(current_code);

disp('----------------------------------------');

end

while attempt <= max_attempts && ~success_val

disp(['第 ', num2str(attempt), ' 次尝试运行...']);

try

evalin('base', current_code);

disp('✓ 代码运行成功!');

success_val = true;

save_code(current_code);

catch ME

disp(['✗ 运行出错: ', ME.identifier]);

disp([' ', ME.message]);

if attempt < max_attempts

disp('正在尝试修复...');

current_code = fix_code(current_code, ME);

disp('修复后的代码:');

disp('----------------------------------------');

disp(current_code);

disp('----------------------------------------');

end

attempt = attempt + 1;

end

end

if ~success_val

disp('已达到最大尝试次数,代码仍无法运行。');

end

end

% ==================== 函数转脚本 ====================

function script_code = convert_function_to_script(func_code)

script_code = strrep(func_code, 'function ', '');

script_code = regexprep(script_code, '^\s*[\w_]+\s*=\s*[\w_]+\s*\(\s*\)', '');

script_code = strrep(script_code, 'end', '');

script_code = strtrim(script_code);

lines = strsplit(script_code, char(10));

new_lines = {};

for i = 1:length(lines)

line = strtrim(lines{i});

if ~isempty(line) && ~(length(line) >= 1 && line(1) == '%')

new_lines{end+1} = line;

end

end

script_code = strjoin(new_lines, char(10));

end

% ==================== 自动修复 ====================

function code = fix_code(code, error_info)

if contains(error_info.message, '未定义函数或变量')

code = ['clear all;', char(10), 'clc;', char(10), code];

elseif contains(error_info.message, '下标索引必须为正整数或逻辑值')

code = strrep(code, 'x = 0', 'x = 1');

elseif contains(error_info.message, '无法打开文件')

code = strrep(code, 'fopen(', 'fopen(''test.txt'', ''w'');fclose(fid);fopen(');

elseif contains(error_info.message, '串联的数组的维度不一致')

code = regexprep(code, 'disp\(\[.*?\]\)', 'disp(''输出内容'')');

elseif contains(error_info.message, '参数数目不足')

code = regexprep(code, 'plot\(', 'plot([0:0.1:10], sin([0:0.1:10]));');

elseif contains(error_info.message, '函数定义在此上下文中不受支持')

code = convert_function_to_script(code);

end

end

% ==================== 保存代码 ====================

function save_code(code)

[filename, pathname] = uiputfile('*.m', '保存生成的代码');

if filename ~= 0

full_path = fullfile(pathname, filename);

fid = fopen(full_path, 'w');

fprintf(fid, '%s', code);

fclose(fid);

disp(['代码已保存到: ', full_path]);

end

end



免责声明:本文系网络转载或改编,未找到原创作者,版权归原作者所有。如涉及版权,请联系删

相关文章
技术文档
QR Code
微信扫一扫,欢迎咨询~
customer

online

联系我们
武汉格发信息技术有限公司
湖北省武汉市经开区科技园西路6号103孵化器
电话:155-2731-8020 座机:027-59821821
邮件:tanzw@gofarlic.com
Copyright © 2023 Gofarsoft Co.,Ltd. 保留所有权利
遇到许可问题?该如何解决!?
评估许可证实际采购量? 
不清楚软件许可证使用数据? 
收到软件厂商律师函!?  
想要少购买点许可证,节省费用? 
收到软件厂商侵权通告!?  
有正版license,但许可证不够用,需要新购? 
联系方式 board-phone 155-2731-8020
close1
预留信息,一起解决您的问题
* 姓名:
* 手机:

* 公司名称:

姓名不为空

姓名不为空

姓名不为空
手机不正确

手机不正确

手机不正确
公司不为空

公司不为空

公司不为空