【发布时间】:2020-09-13 02:17:37
【问题描述】:
我目前正在学习 Andrew Ng 的斯坦福机器学习课程,并且正在使用 MATLAB 来完成编程作业,尽管我是 MATLAB 编程语言的新手,因为该课程需要在 Ocatave 或 MATLAB 中完成作业。对于第一个编程作业,本课程提供 Octave/MATLAB 脚本,指导您完成练习。我正在尝试编写一个 MATLAB 函数来绘制 x 和 y 变量的数据,但是,我继续遇到相同的错误,并开始寻找解决方案。我有一个正在处理的 plotData.m 文件,这是我整理的代码:
function plotData(x, y)
%PLOTDATA Plots the data points x and y into a new figure
% PLOTDATA(x,y) plots the data points and gives the figure axes labels of
% population and profit.
figure; % open a new figure window
hold on;
% ====================== YOUR CODE HERE ======================
% Instructions: Plot the training data into a figure using the
% "figure" and "plot" commands. Set the axes labels using
% the "xlabel" and "ylabel" commands. Assume the
% population and revenue data have been passed in
% as the x and y arguments of this function.
%
% Hint: You can use the 'rx' option with plot to have the markers
% appear as red crosses. Furthermore, you can make the
% markers larger by using plot(..., 'rx', 'MarkerSize', 10);
plot(x, y, 'rx');
xlabel('population (in tens of thousands)');
ylabel('profit (in $10,000s)');
hold off;
% ============================================================
end
每次运行此脚本时,我都会收到一条错误消息,指出“输入参数不足。 plotData 错误(第 19 行) plot(x, y, 'rx');'。这是一个相当模糊的错误消息,我不确定如何解释这里出了什么问题。我不明白为什么在这个例子中我没有足够的输入参数,因为函数显式地接受 x 和 y 并使用每个来绘制函数定义的数据。任何帮助将不胜感激。
我使用的是 MATLAB 版本 9.6.0.1114505 (R2019a) 更新 2
【问题讨论】:
-
您的代码应该可以运行。在第 19 行放置一个断点,然后进入
plot(x, y, 'rx');(使用调试器)。尝试执行:x = -pi:0.1:pi;y = sin(x);plotData(x, y);只是为了确保x和y有效。 -
你写的不是脚本,而是函数。你是怎么调用函数的?
-
@CrisLuengo Executing which plot return 'built-in (/Applications/MATLAB_R2019a.app/toolbox/matlab/graph2d/plot)' - 我没有用另一个文件或变量隐藏绘图函数跨度>
-
@Rotem Executing
x = -pi:0.1:pi;y = sin(x);plotData(x, y);at line 19 beforeplot(x, y, 'rx');在 MATLAB 崩溃和退出之前运行了大约 15 分钟。此外,我不确定为什么当我删除函数中的变量赋值时,函数不会无错误地运行。最终目标是能够在任何时候使用函数并在那个时候定义 x 和 y,而不是在函数本身内。我不确定我在这里缺少什么? -
重复@David 的问题很重要:你是如何调用函数
plotData的?如果您尝试仅通过按下 matlab 菜单中的绿色 [RUN] 按钮来运行调用该函数,您将收到此错误。您需要在工作区(或另一个函数)中定义x和y,然后只有您可以从那里调用plotData(x, y)(工作区或定义x和y的函数)。