Matrix multiplication error although dimensions match

조회 수: 3 (최근 30일)
BJHM
BJHM 2020년 4월 21일
댓글: BJHM 2020년 4월 21일
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!

답변 (2개)

Mehmed Saad
Mehmed Saad 2020년 4월 21일
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
BJHM
BJHM 2020년 4월 21일
You're right! I fixed the function and now it works :)
Thank you!

댓글을 달려면 로그인하십시오.


Ameer Hamza
Ameer Hamza 2020년 4월 21일
편집: Ameer Hamza 2020년 4월 21일
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
BJHM
BJHM 2020년 4월 21일
That was the issue. I fixed the function and now it works :)
Thank you!

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by