Is the Order of Function Evaluation Guaranteed when Function Outputs are Concatenated into an an Array?
Afficher commentaires plus anciens
Suppose I call two functions within concatenation into an array
A = [ones(1,2),zeros(1,2)]
In this case, the order in which ones and zeros are evaluated doesn't matter as far as the result is concerned.
But what about when there is dependence between the two (or more) functions whose outputs are being concatenated:
A = [figure,plot(1:3)]
Is there any guarantee that the call to figure is evaluated and the figure created before the call to plot so that the plotted result is in the newly created figure?
Does the answer change if creating a cell array?
A= {figure,plot(rand(2))}
Réponse acceptée
Plus de réponses (1)
This reasoning might not be bulletproof, but I think the order of funtion calls in any expression has to always go left to right due to rules of precedence. In other words, in an expression like this,
ans = funcA()+funcB()+funcC()
we know that the first addition on the right hand side has to be evaluated first, and therefore funcA() and funcB() have to be available for that. There are ways you can satisfy rules of precedence with the funcx() evaluated in an arbitrary order, but only by temporarily storing all three funcx() outputs simultaneously. But I just don't think they would do that. Programmers want to be able to count on the result of funcA()+funcB() being transient, so that they can predict peak RAM consumption. Tempory caching of all function calls would upset that, especially if the outputs of the funcx() happen to be large arrays.
In addition, there is the test below. No matter how many times I run, I cannot generate an occurence of non-consecutive evaluations.
h=subtest;
f=@() issorted(cell2mat({h(),h(),h(),h(),h(),h(),h(),h(),h(),h(),h(),h(),h()}));
N=2e4;
isConsecutive=false(N,1);
for i=1:N
isConsecutive(i)=f();
end
tf=all(isConsecutive) %Check if result was conseuctive in all cases
function h=subtest
i=0;
h=@increment;
function j=increment()
i=i+1;
j=i;
end
end
1 commentaire
Paul
le 10 Jan 2026
Catégories
En savoir plus sur Matrix Indexing dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!





