2015-04-07 69 views
5

我有一个简单的数据文件看起来像这样:八度/ Matlab的 - 不能/绘图数据

data.txt 
34.62365962451697,78.0246928153624,0 
30.28671076822607,43.89499752400101,0 
35.84740876993872,72.90219802708364,0 
60.18259938620976,86.30855209546826,1 
79.0327360507101,75.3443764369103,1 

,我试图用下面的代码绘制它的数据:

data = load('data.txt'); 
X = data(:, [1, 2]); y = data(:, 3); 

plotData(X, y); 

hold on; 

xlabel('Exam 1 score') 
ylabel('Exam 2 score') 

legend('Admitted', 'Not admitted') 
hold off; 

pause; 

然而,这给我带来以下错误:

warning: legend: plot data is empty; setting key labels has no effect 
error: legend: subscript indices must be either positive integers less than 2^31 or logicals 

没有东西被绘制。

我不明白什么是错的。工作目录在八度中很好。

我该如何解决这个问题?

非常感谢

+1

我想你需要在那里使用单元阵列 - 'legend({'Admitted','Not admit'})'。 – Divakar

+0

我试过,但它仍然不工作:( – Spearfisher

+1

打印'X'和'y'时会得到什么?它们真的是空的吗?另外,请尝试使用[csvread](http://www.mathworks.com/help/) matlab/ref/csvread.html)而不是[load](http://www.mathworks.com/help/matlab/ref/load.html)。Load是存储在文件中的matlab变量。 – eventHandler

回答

3

1)X是一个5×2阵列,而y是一个5X1阵列

2)plotData是不是一个Matlab的命令,使用情节代替

尝试以下代码:

data = load('data.txt'); 
x1 = data(:, 1); 
x2 = data(:,2); 
y = data(:, 3); 

plot(x1, y); 
hold on 
plot(x2,y); 

xlabel('Exam 1 score') 
ylabel('Exam 2 score') 

legend('Admitted', 'Not admitted') 
hold off; 
pause; 
4

如果您仔细阅读pdf,PlotData.m代码位于pdf中。 下面是代码:

% Find Indices of Positive and Negative Examples 
pos = find(y==1); neg = find(y == 0); 
% Plot Examples 
plot(X(pos, 1), X(pos, 2), 'k+','LineWidth', 2, 'MarkerSize', 7); 
plot(X(neg, 1), X(neg, 2), 'ko', 'MarkerFaceColor', 'y','MarkerSize', 7); 
0

您试图在机器由安德鲁·吴对coursera学习课程三个星期分配。在ex2.m文件中,有一个调用函数plotData(X,y),它指向写在plotData.m文件中的函数。您可能认为plotData是八度音阶的默认函数,但您实际需要在plotData.m文件中实现该函数。 这是我在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 with + for the positive examples 
% and o for the negative examples. X is assumed to be a Mx2 matrix. 

% Create New Figure 
figure; hold on; 

% ====================== YOUR CODE HERE ====================== 
% Instructions: Plot the positive and negative examples on a 
%    2D plot, using the option 'k+' for the positive 
%    examples and 'ko' for the negative examples. 
% 

pos = find(y==1); 
neg = find(y==0); 
plot(X(pos, 1), X(pos, 2), 'k+','LineWidth', 2, ... 
'MarkerSize', 7); 
plot(X(neg, 1), X(neg, 2), 'ko', 'MarkerFaceColor', 'y', ... 
'MarkerSize', 7); 

% ========================================================================= 



hold off; 

end