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

7 次查看(过去 30 天)
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 个评论
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 CenterFile Exchange 中查找有关 Operating on Diagonal Matrices 的更多信息

产品


版本

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by