MATLAB: Trouble with if statement

if

I am trying to write a statement that if r>n2 then i require an error message to be displayed otherwise i need it to continue on and carry out the rest of the algorithm. For examples which r<n2 the code works but for r>n2 the message is displayed but an error messages stating rep not assigned is also appearing. not sure what im doing wrong. any help appreciated. here is my code:
function [rep]=assign(B)
[r,c]=size(B) % dimension of matrix. r will be number of students
W = B(:); % produces matrix in one long vector
n=length(W); %total number of elements in matrix
Projects2 = unique(W); % identifies which projects were chosen
n2=length (Projects2) % number of projects chosen
if r<n2,
[a,b]=hist(W,unique(W)); %
z2=[a',b]; % prodcuces a vector showing projects preferenced in second column and the number of times they have been preferenced in first column
rep=sortrows(z2,1); %sorts matrix by number of repetitions
else
disp(['Error: The number of students exceeds number of projects'])
return
end
end

Best Answer

  • The error is correct; if you take the else branch then nothing is assigned to rep and you didn't use varargout so it expects something. The simplest solution is to simply add
    rep=[];
    as the last statement before returning in the else clause. This also gives the opportunity to use
    isempty(assign(x))
    at the calling level or similar to discern success programmatically which is often handy.