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 Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by