Nisitha Jayatilleka
Nisitha Jayatilleka

Reputation: 741

Matlab exp only works on the first element?

I've been trying to get a simple sigmoid function to work in matlab and it seems it only works for the first element of the matrix.

my code is:

function g = sigmoid(z)
    g = zeros(size(z));
    g = 1/(1 + exp(-z));
end

Now it works fine for simple values like:

>>sigmoid(0)
ans = 0.5000

but for: `

>>k = [0; 0; 0; 0; 0];
>>sigmoid(k)`

it's giving me:

ans = 0.5000 0 0 0 0

looking into 'exp' it says its an element-wise operation, so I am not sure where I am going wrong. Any help would be appreciated. :)

Upvotes: 1

Views: 51

Answers (1)

Suever
Suever

Reputation: 65460

A few issues here.

  1. You don't need to pre-allocate g only to reassign it in the next line.

  2. You need to use element-wise division ./ rather than matrix division /

So the correct function would be:

function g = sigmoid(z)
    g = 1 ./ (1 + exp(-z));
end

Upvotes: 1

Related Questions