create perceptron algorithm in matlab

Here is an implementation of the perceptron algorithm in MATLAB:

main.m
% Initialize the data
X = [0 0 1; 0 1 1; 1 0 1; 1 1 1];
y = [0; 0; 0; 1];

% Initialize the weights
w = randn(size(X, 2), 1);

% Set the learning rate
alpha = 0.1;

% Perform the perceptron algorithm
for i = 1:1000
    % Choose a random data point
    idx = randi(size(X, 1));
    x_i = X(idx, :)';
    y_i = y(idx);

    % Compute the activation
    z_i = w'*x_i;
    a_i = 1/(1+exp(-z_i));

    % Update the weights
    d_w = alpha*(y_i-a_i)*a_i*(1-a_i)*x_i;
    w = w + d_w;
end

% Test the perceptron
X_test = [1 1 1; 1 0 1; 0 1 1; 0 0 1];
for i = 1:size(X_test, 1)
    x_i = X_test(i, :)';
    z_i = w'*x_i;
    a_i = 1/(1+exp(-z_i));
    fprintf('Input: %s\tOutput: %f\n', mat2str(x_i'), a_i);
end
704 chars
35 lines

This implementation performs the perceptron algorithm on the given data, updates the weights using stochastic gradient descent, and tests the resulting model on new data.

gistlibby LogSnag