How would I return a matrix from a function?
조회 수: 98 (최근 30일)
이전 댓글 표시
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
the cyclist
2018년 10월 31일
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);
답변 (2개)
TADA
2018년 10월 31일
편집: TADA
2018년 10월 31일
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();
댓글 수: 0
the cyclist
2018년 10월 31일
편집: the cyclist
2018년 10월 31일
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".
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!