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

15 views (last 30 days)
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 Comments
Lakerpurp24
Lakerpurp24 on 20 Feb 2020
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]

Sign in to comment.

Accepted Answer

Walter Roberson
Walter Roberson on 20 Feb 2020
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 Comments
Lakerpurp24
Lakerpurp24 on 20 Feb 2020
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 on 20 Feb 2020
[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.

Sign in to comment.

More Answers (0)

Categories

Find more on Operating on Diagonal Matrices in Help Center and File Exchange

Products


Release

R2019a

Community Treasure Hunt

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

Start Hunting!