1

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. :)

1 Answers1

1

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
Suever
  • 64,497
  • 14
  • 82
  • 101