专栏
标签
Syslab中定义函数报错UndefVarError: ‘XX’ not defined
技术分享
发布于 2025-08-06 16:42:18
查看 2过去300天

问题现象

调用 function 功能自定义的函数 linear_tmp 时,报 UndefVarError: linear_tmp not defined 错误

自定义函数示例代码:

function y = linear_tmp(x)
    a = 3
    y = a*x + b
end

image.png

调用函数示例代码:

x = [1 2 3]
y = linear_tmp(x)
figure;
plot(x,y)

运行结果:
image.png

解决方法

1.Julia自定义函数返回不能写在函数名处,需要用 return 关键字去返回,选中自定义函数后按 ctrl+enter 或 shift+enter 可以识别出这个函数即定义成功;

示例代码:

function linear_tmp(x)
    a = 3
    b = 2
    y = a*x + b
    return y
end

image.png

2.函数定义在一个独立的Julia脚本文件中时,需要通过 include 将包含函数定义的文件先加载到当前脚本中,之后才可以跳转对应自定义函数

示例代码:

include("D:/MWORKS/test/linear_tmp.jl")
aa = linear_tmp(2)

运行结果:
image.png

当x为向量时,需将 自定义函数中 y = ax + b 改为 y = ax .+ b;如下所示:

#自定义函数
function linear_tmp(x)
    a = 3
    b = 2
    y = a*x .+ b
    return y
end

#调用 linear_tmp 函数
include("D:/MWORKS/test/linear_tmp.jl")
x = [1 2 3]
y = linear_tmp(x)
figure;
plot(x,y)

运行结果:
image.png

可以通过在 Syslab 中查看帮助文档了解 function 的使用方式:
image.png

Julia命令行中 按住 shift+?进入 help mode ,输入include,即可查看 include 的帮助信息:
image.png

所属专栏:Sysplorer基础平台
产品信息:Sysplorer系统建模仿真环境
系统建模

全部回答

暂无数据
暂无数据
用户
和原帖交流更多问题细节吧,去
我要发帖 我要发帖
资料中心 资料中心
查看更多>
热门帖子 热门帖子
主要贡献者 主要贡献者
过去7天