【问题标题】:Matlab external .m file function returnMatlab外部.m文件函数返回
【发布时间】:2018-02-09 23:35:24
【问题描述】:

我有 Main.m 和 External.m

我想从 Main.m 调用 External.m 中的一个函数

Main.m 代码:​​

clc
External
disp('Press any key to go to advance')
pause

外部.m代码:

function f=EPD470_ObermeierC_Lesson05_MFile
    x=0:4:40
end

它确实正确显示了我想要的值:

x =
 0     4     8    12    16    20    24    28    32    36    40

但随后抛出错误:

在调用期间未分配输出参数“f”(可能还有其他参数) “EPD470_ObermeierC_Lesson05_MFile”。

编辑:

我正在尝试在 Main.m 中显示 External.m 返回的值

变化

Main.m 代码:​​

clc
y=External
disp(y)
pause

(已编辑以反映错字) 外部.m 代码:​​

function f=External
    f=0:4:40
end

它没有显示我想要的值。

【问题讨论】:

  • 错误信息有什么不清楚的地方?您的函数使用输出 f 声明,而您从未定义 f
  • x=0:4:40改成f=0:4:40,别忘了把返回值赋给函数外的东西。
  • @excaza。凭借多年的经验,很容易阅读错误消息。当你第一次开始时,这很可怕。我只是感谢这个人发布所有相关信息并努力打印x。当然,这个问题非常幼稚,但只要它是适当的,这不是犯罪。
  • @MadPhysicist 我将 External.m 文件更改为您建议的内容。我正在尝试在 Main 中显示 y 值。米。所以我将代码更改为 y=External,但它不会自动显示 y。然后我尝试了 disp(y) ,但它也没有显示该值。抱歉,这是一个新手问题,但我无法弄清楚我错过了什么。
  • @obizues。为您的问题添加后续编辑,显示您的具体尝试。不要修改问题的原始部分,因为除了修复转录错误之外,代码修改是非常糟糕的形式。

标签: matlab


【解决方案1】:

欢迎使用 MATLAB!希望你喜欢这种语言。

您将在下面找到 External.m 和 Main.m(Main.m 的两个选项)的更新代码,其中包含许多解释为什么建议更改的 cmets。

外部.m:

% generally it's best practice to name the function the same as in the
% filename. This won't impact the running of the code
function f = External

% change the main line of the function to assign the value to the correct
% variable name. Also, add a semicolon to the end of this line to suppress
% output (when a variable is assigned in MATLAB in a line that does not
% end in a semicolon, the MATLAB console displays that variable)
f = 0:4:40;

% the end command isn't necessary if just one function is defined in the
% file. Again, it won't impact the running of the code, but for simplicity
% it may be preferable to omit

Main.m - 选项 1:

% unchanged
clc

% assign the output of External to a variable. Note that the name of the
% variable used here may be the same as used inside the function, or it may
% not be the same. Note also that a semicolon is used to suppress output
x = External;

% explicitly display the variable
disp(x);

% unchanged
disp('Press any key to go to advance')
pause

Main.m - 选项 2:

% unchanged
clc

% assign the output of External to a variable. Note that the name of the
% variable used here may be the same as used inside the function, or it may
% not be the same. The absence of a semicolon on a line where a variable
% is assigned means that the MATLAB console will display that variable
x = External

% unchanged
disp('Press any key to go to advance')
pause

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-19
    • 1970-01-01
    • 1970-01-01
    • 2015-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多