function [L,X]=eigenSM(K,M,b,k)
% Niklas Ivarsson 2018-01-23
%
%-------------------------------------------------------------
% PURPOSE
%  Solve the generalized eigenvalue problem
%  [K-LM]X = 0, considering boundary conditions.
%  ---> Specified number of eigenvalues considered.
%
%
% INPUT:
%    K : global stiffness matrix, dim(K)= nd x nd
%    M : global mass matrix, dim(M)= nd x nd
%    b : boundary condition matrix
%        dim(b)= nb x 1
%    k : specifies the number of smallest eigenvalues to be returned 
%
% OUTPUT:
%    L : eigenvalues stored in a vector with length k
%    X : eigenvectors dim(X)= nd x k
%-------------------------------------------------------------

% LAST MODIFIED: H Carlsson  1993-09-21
% Niklas Ivarsson 2018-01-23
% Copyright (c)  Division of Structural Mechanics and
%                Department of Solid Mechanics.
%                Lund Institute of Technology
%-------------------------------------------------------------
nd=size(K,1);
fdof=[1:nd]';  % all dofs
pdof=b(:);     % all boundary dofs
fdof(pdof)=[]; % exclude the above dofs from fdof


[X1,D]=eigs(K(fdof,fdof),M(fdof,fdof),k,'SM');
nfdof=k;

for j=1:nfdof
    mnorm=sqrt(X1(:,j)'*M(fdof,fdof)*X1(:,j));
    X1(:,j)=X1(:,j)/mnorm;
end
d=diag(D);
[L,i]=sort(d);
X2=X1(:,i);
X=zeros(nd,nfdof);
X(fdof,:)=X2;
%--------------------------end--------------------------------
