Filter löschen
Filter löschen

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

7 Ansichten (letzte 30 Tage)
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 Kommentare
Lakerpurp24
Lakerpurp24 am 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]

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Walter Roberson
Walter Roberson am 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 Kommentare
Lakerpurp24
Lakerpurp24 am 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 am 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.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Operating on Diagonal Matrices finden Sie in Help Center und File Exchange

Produkte


Version

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by