How to return an individual matrix from a function that uses multiple?

5 ビュー (過去 30 日間)
Lakerpurp24
Lakerpurp24 2020 年 2 月 20 日
コメント済み: Walter Roberson 2020 年 2 月 20 日
I have a nested parent function that operates on multiple matrices using other functions. I then want to return individual matrixes to others. Ive listed toy code below as a general example of what im trying to do:
% id like to return these matrices in a wat so that i could assign them elsewhere like:
% g = fun(d)
function fun1 = fun(a, b,c,n)
for i = 1:1:lentgth (n)
d(i) = add(a(i),b(i));
e(i) = subtract(a(i),c(i));
f(i) = multiply(b(i),c(i));
end
end
  3 件のコメント
Walter Roberson
Walter Roberson 2020 年 2 月 20 日
What role does n play in the function?
Lakerpurp24
Lakerpurp24 2020 年 2 月 20 日
a, b, and c are matrices of length n.
what they are doesnt matter. think of a = [1,2,3] , b = [4,5,6] c = [7,8,9]

サインインしてコメントする。

採用された回答

Walter Roberson
Walter Roberson 2020 年 2 月 20 日
On your code whatever you assign to fun1 would be returned. You can also do things like
function [d, e, f] = fun(a, b, c, n)
And then three matrices would be returned positionally.
  3 件のコメント
Lakerpurp24
Lakerpurp24 2020 年 2 月 20 日
alternatively, is there a way to run the function without assigning it so that d, e, and f get stored in my workspace without assigning the function?
can i execute a function call without setting it equal to a variable?
Walter Roberson
Walter Roberson 2020 年 2 月 20 日
[mat1, mat2, mat3] = fun(a, b, c, n)
Use your choice of output variable names.
Yes there is a way to assign into the workspace so that you do not need to use assignments. However that is seldom good programming, and MATLAB is increasingly making changes that lead to odd outcomes when you do such a thing. The short explanation is that the execution engine optimization phase is notably less efficient when MATLAB needs to take into account assignments that are not obvious in the code being executed, so Mathworks is increasingly saying "ok, we'll let that kind of behaviour break in favour of the greater efficiency!" In the fine details, the optimization is making choices more like a compiler and less like an interpreter. The kind of assignment that you want to do used to be fine when MATLAB always choose consistency with interpreter over efficiency.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

製品


リリース

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by