2015-04-07 68 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