Hello!
I am curious if this is possible. Say I write a function
function F = func(x)
F(1) = x(1)-cos(x(2));
F(2) = x(2)-cos(x(1));
end
Now every time I call on this function it calculates the RHS of the equation and gives an output for F. Now if I had a ton of calculations before F that I don't want Matlab to constantly repeat, all I want is the last statement F.
An example would be
function F = func(x)
% I send the x vector in order to get boundary conditions
BC = Boundaries(x);
% Now BC is a function with equations like BC(1) = x(1)+x(2)... etc
F(1) = BC(1);
F(2) = BC(2);
end
I want to use the function F(1) = x(1)+x(2), and not have to constantly send x to BC to "create" those equations.

댓글 수: 5

Guillaume
Guillaume 2018년 9월 11일
편집: Guillaume 2018년 9월 11일
I'm afraid I don't really understand what you're asking. What does to "create" those equations actually mean?
You can pass a function to use to another function if that's what you're after (i.e. you could pass different BC functions to func).
Kristoffer Lindvall
Kristoffer Lindvall 2018년 9월 11일
Yes, the point is that every time I call on func(x) Matlab sends the x values to BC as well, and then to F. I would like to be able to create functions somewhere else once, and then set F equal to those functions, then have Matlab only evaluate F.
Imagine if the BC function takes a lot of CPU time to create the equations x(1)+x(2)... etc. I only want the result of BC. I don't want to go through the process of making BC. As far I have understood it, Matlab goes through BC every time I need to evaluate F. Even if I create BC somewhere else, it still goes through BC and all that that function has inside it to output a result.
I think the problem is that the function isn't creating equations, but more like a path that x values go through. This is really hard to explain I apologize.
You can create BC once and then pass it to func:
BC=Boundaries(2); %creating BC once
F=func(1:3,BC);
function BC=Boundaries(x)
BC=1:3+x; %some heavy calculations
end
function F=func(x,BC) %passing BC aswell
F(1)=BC(1)+x(2);
end
Stephen23
Stephen23 2018년 9월 11일
편집: Stephen23 2018년 9월 11일
Then why not just move Boundaries outside of func and calculate it only once?
Guillaume
Guillaume 2018년 9월 11일
Still not entirely clear on what is being asked, not helped by the imprecise terms used. You don't make functions. Functions don't create equations. You call a function with some inputs and it returns some outputs.
In addition to what has already been suggested, since R2017a, there is also the possibility of memoizing a function, a technique that caches the results of a function that is expensive to run so that it is only run if different inputs are provided. No idea, if that's what you're after.

댓글을 달려면 로그인하십시오.

답변 (0개)

질문:

2018년 9월 11일

댓글:

2018년 9월 11일

Community Treasure Hunt

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

Start Hunting!

Translated by