How would I return a matrix from a function?

234 views (last 30 days)
function x = fSub(A, b)
n = size(A);
x = zeros(n,1);
x(1,1) = b(1,1)/A(1,1);
x(2,1) = (b(2,1)-(A(2,1)*x(1)))/A(2,2);
for i = 3:n
x(i,1) = (b(i,1)-(A(i,i-1)*x(i-1,1)))/A(i,i);
end
return x;
end
If I give this function An n*n matrix A and n*1 matrix b, how can I return the newly created matrix x? I'm getting an invalid expression error at the return line.
  1 Comment
the cyclist
the cyclist on 31 Oct 2018
FYI, if A is an N*N matrix, then the code
n = size(A);
x = zeros(n,1);
is going to error out, because it will result in
x = zeros([N N],1);
which is incorrect syntax.
I think you actually want
n = size(A);
x = zeros(n);

Sign in to comment.

Answers (2)

TADA
TADA on 31 Oct 2018
Edited: TADA on 31 Oct 2018
In matlab you don't return values using the return statement you simply need to set the value of each out arg (yes functions may return more than one argument...)
in general it looks like that:
function x = foo()
x = zeros(10, 10);
end
the above function returns a 10x10 matrix.
the return statement simply stops the function immediately, but is generally not mandatory for your function
like i mentioned above, the function may return more than one argument like that:
function [x1, x2, x3] = foo()
x1 = rand(1); % returns a scalar
x2 = rand(1, 10); % returns a 1x10 vector
x3 = rand(10, 10); % returns a 10x10 matrix
end
and the code for calling that function should look like that:
[x1, x2, x3] = foo();
% or you're only interested in some of the return values you can always take only part of it:
[x1, x2] = foo();

the cyclist
the cyclist on 31 Oct 2018
Edited: the cyclist on 31 Oct 2018
You don't need the
return x
line at all.
The first line of the function already tells MATLAB to return the value stored in x.
The return function in MATLAB just means "return to the invoking function now, without executing the lines after this one".

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!