Matrix multiplication error although dimensions match

3 visualizzazioni (ultimi 30 giorni)
BJHM
BJHM il 21 Apr 2020
Commentato: BJHM il 21 Apr 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!

Risposte (2)

Mehmed Saad
Mehmed Saad il 21 Apr 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

Ameer Hamza
Ameer Hamza il 21 Apr 2020
Modificato: Ameer Hamza il 21 Apr 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.

Community Treasure Hunt

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

Start Hunting!

Translated by