% assembling of the stiffness matrix and the load vector for a given mesh
% in 1D

function [K,f_vec] = assembling(nodes,lambda,f)
    n_nodes = length(nodes);
    K = zeros(n_nodes);
    f_vec = zeros(n_nodes,1);
    h_diff_vec = nodes(2:end) - nodes(1:end-1); % step width
    for k = 1:n_nodes-1
        % stiffness matrix
        lambda_int = integral(lambda, nodes(k), nodes(k+1));
        K_loc = lambda_int/h_diff_vec(k)^2*[1,-1;-1,1];
        K(k:k+1,k:k+1) = K(k:k+1,k:k+1) + K_loc;
        % right hand side
        phi_left = @(x) (nodes(k+1)-x)/h_diff_vec(k).*f(x);
        phi_right = @(x) (x-nodes(k))/h_diff_vec(k).*f(x);
        f_loc = [integral(phi_left,nodes(k),nodes(k+1)); integral(phi_right,nodes(k),nodes(k+1))];
        f_vec(k:k+1) = f_vec(k:k+1) + f_loc;
    end
end