Cannot get multiple outputs on matlab function

1 view (last 30 days)
I have two functions below (the first one calls the second one) and it only gives one output
function [theta, J_history, Tet1, Tet2] = gradientDescent(X, y, theta, alpha, num_iters)
% Initialize some useful values
m = length(y); % number of training examples
J_history = zeros(num_iters, 1);
for iter = 1:num_iters
temp0 = 0;
temp1 = 0;
for i = 1:m
temp0 = temp0 + (theta' * X(i,:)' - y(i));
temp1 = temp1 + (theta' * X(i,:)' - y(i)) * X(i,2);
end
theta(1) = theta(1) - (alpha/m) * temp0;
theta(2) = theta(2) - (alpha/m) * temp1;
Tet1(iter,1)=theta(1);
Tet2(iter,1)=theta(2);
% Save the cost J in every iteration
J_history(iter) = computeCost(X, y, theta);
end
end
And second function'
function J = computeCost(X, y, theta)
m = length(y); % number of training examples
J = 0;
for i = 1:m
J = J + (theta' * X(i,:)' - y(i))^2;
end
J = J/(2*m);
end

Answers (1)

Steven Lord
Steven Lord on 10 Aug 2019
How many output arguments do you specify when you call gradientDescent?
If you don't specify any, the first output gradientDescent is declared to return (theta) is returned and stored in the variable named ans.
If you specify one like "myOut = gradientDescent(...)", the theta variable computed by gradientDescent is returned and stored in that variable.
If you specify two like "[myOut1, myOut2] = gradientDescent(...)", theta is returned and stored in the first of your output arguments, while J_history is returned and stored in the second of your output arguments.
That pattern continues for three and four output arguments.

Community Treasure Hunt

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

Start Hunting!