function [ u, changes ] = dwelling( v )

% v= input vector (raw data consisting of zeros and ones)

    u=unique(v);            % all states of the vector
    d=diff(v);              % all transitions
    tr=unique(d);           % unique transitions
    tr=tr(find(tr));        % find transitions to different states
    
    if isempty(tr)
        changes=[length(v), v(1)]; 
    else
        
        changes=[];
   
        for i=1:length(tr)      % for each different state transition find indices and arrange by time
            temp=find(d==tr(i)); 
            temp=[temp, v(temp)];
            changes=vertcat(changes,temp); 
        end
        [~,i]=sort(changes(:,1), 'ascend');
        changes=changes(i,:);
        if changes(1,1)~=1
            changes=vertcat([0, v(1)], changes);
        end
        changes=vertcat(changes, [length(v), v(end)]);
        changes=[diff(changes(:,1), 1), changes(2:end,2)];
    end
end

