aceminer
aceminer

Reputation: 4295

Allowing inputs to be matrix or vectors or scalar in octave

I am doing the coursera machine learning logistic regression assignment and I wrote the top piece of code.

Instructions

function g = sigmoid(z)
%SIGMOID Compute sigmoid functoon
%   J = SIGMOID(z) computes the sigmoid of z.

% You need to return the following variables correctly 
g = zeros(size(z));

% ====================== YOUR CODE HERE ======================
% Instructions: Compute the sigmoid of each value of z (z can be a matrix,
%               vector or scalar).



g = (1 / (1 + exp(-1 * z)) ) .^ 1;

%g = (1 + exp(-1 * z)) .^ -1;
% =============================================================

end

My Code --- Breaks when inputting a vector or matrix

g = (1 / (1 + exp(-1 * z)) ) .^ 1;

I found this code on some github ---- Works for all cases

g = (1 + exp(-1 * z)) .^ -1;

The issue is the output works when my input is a scalar. My code breaks when it becomes a vector. May i know what am i missing as it appears to me to be the same

Upvotes: 0

Views: 439

Answers (1)

Suever
Suever

Reputation: 65430

You need to change / which is a matrix right division to be an element-wise division (./)

g = (1 ./ (1 + exp(-1 * z)) ) .^ 1;

The use of / will work just fine for scalars, but when one of the inputs is a matrix (in this case the right side of the operator), the meaning changes and you will get either an error or unexpected results.

Upvotes: 1

Related Questions