Matrix multiplication error although dimensions match

3 visualizaciones (últimos 30 días)
BJHM
BJHM el 21 de Abr. de 2020
Comentada: BJHM el 21 de Abr. de 2020
Hi everyone,
I'm trying to multiply the matrix X (dimensions: 100x3) and the vector initial_theta (dimensions: 3x1) by computing
X*initial_theta
When I type this in the command window, it works as expected and returns a 100x1 array.
However, when I call the function costFunction (see code below) I get this error:
[cost, grad] = costFunction(initial_theta, X, y);
Code of costFunction:
function [J, grad] = costFunction(theta, X, y)
%COSTFUNCTION Compute cost and gradient for logistic regression
m = size(X,1);
X = [ones(m,1),X];
J = 0;
grad = zeros(size(theta,1),1);
h = sigmoid(X*theta);
J = -(1 / m) * sum(y .* log(h) + (1 - y) .* log(1 - h));
for i = 1 : size(grad),
grad(i) = (1/m)*sum( (h-y)' * X(:,i) );
end
The sigmoid function looks as follows:
function g = sigmoid(z)
%SIGMOID Compute sigmoid function
% g = SIGMOID(z) computes the sigmoid of z.
g = zeros(size(z));
g = 1 ./ (1 + exp(-z));
end
I already tried changing the dimensions of X and initial_theta, but as expected it didn't fix the problem since the dimensions are already matching.
Does anyone have an idea as to what might be causing this error?
Your help is greatly appreciated!

Respuestas (2)

Mehmed Saad
Mehmed Saad el 21 de Abr. de 2020
You added another dimension in X here
X = [ones(m,1),X];
Try this in cmd
X = rand(100,3);
X = [ones(size(X,1),1),X];
size(X)
ans =
100 4
  1 comentario
BJHM
BJHM el 21 de Abr. de 2020
You're right! I fixed the function and now it works :)
Thank you!

Iniciar sesión para comentar.


Ameer Hamza
Ameer Hamza el 21 de Abr. de 2020
Editada: Ameer Hamza el 21 de Abr. de 2020
Because in the function you are appending a column of ones in this line
X = [ones(m,1),X];
which makes X a matrix of size 100x4, which cannot be multiplied to 3x1 vector.
  1 comentario
BJHM
BJHM el 21 de Abr. de 2020
That was the issue. I fixed the function and now it works :)
Thank you!

Iniciar sesión para comentar.

Categorías

Más información sobre Matrix Indexing en Help Center y File Exchange.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by