Matrix multiplication error although dimensions match
11 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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!
0 commentaires
Réponses (2)
Mehmed Saad
le 21 Avr 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
le 21 Avr 2020
Modifié(e) : Ameer Hamza
le 21 Avr 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.
Voir également
Catégories
En savoir plus sur Matrix Indexing dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!