Subscript indices must either be real positive integers or logicals.
1 view (last 30 days)
Show older comments
Hi everyone, I am trying to implement the K-Nearest Neighboors (K-NN) function and I have trouble understanding the error. I have looked at the forum of Mathworks already but didn't find answer of my problem. I tried to cast "idx(:)" to int16 but it still didn't work. Can anyone help me fix this problem and help me understand the reason why it doesn't work? Thanks!
function [ y_est ] = my_knn(X_train, y_train, X_test, k, type)
%MY_KNN Implementation of the k-nearest neighbor algorithm
% for classification.
%
% input -----------------------------------------------------------------
%
% o X_train : (N x M_train), a data set with M_test samples each being of dimension N.
% each column corresponds to a datapoint
% o y_train : (1 x M_train), a vector with labels y \in {0,1} corresponding to X_train.
% o X_test : (N x M_test), a data set with M_test samples each being of dimension N.
% each column corresponds to a datapoint
% o k : number of 'k' nearest neighbors
% o type : (string), type of distance {'L1','L2','LInf'}
%
% output ----------------------------------------------------------------
%
% o y_est : (1 x M_test), a vector with estimated labels y \in {0,1}
% corresponding to X_test.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
[N,M_train]=size(X_train);
[N,M_test]=size(X_test);
d=zeros(M_test,M_train);
y_est=zeros(1,M_test);
B=zeros(1,k);
for test=1:M_test
for train=1:M_train
d(test,train)=my_distance(X_train(:,train),X_test(:,test), 'L2');
end
%find the k minimum value for each line
val=zeros(k);
idx=zeros(k);
for i=1:k
[val(i),idx(i)]=min(d(test,:));
d(test,idx(i))=max(d(test,:));
end
y_est(1,test)=mode(y_train(idx(:)));
end
end
Here is the error that still appear:
_Subscript indices must either be real positive integers or logicals.
Error in my_knn (line 38) y_est(1,test)=mode(y_train(idx(:)));_
0 Comments
Answers (1)
Image Analyst
on 31 Oct 2016
Use the debugger to step through and find out what the values of idx are. They can't be 0, negative, or fractional numbers. See the FAQ: http://matlab.wikia.com/wiki/FAQ#Why_is_0.3_-_0.2_-_0.1_.28or_similar.29_not_equal_to_zero.3F
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!