How would I return a matrix from a function?
234 ビュー (過去 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!