Creation and evaluation of a variable containing a variable in reasonable time
Info
This question is closed. Reopen it to edit or answer.
Show older comments
I am currently trying to get a fast code that is as flexible as possible but i am facing a problem that is apparently tricky :
I want to create a variable matrix A that changes in time.
let's assume
A = [1 -t; 2 t];
If i did not specify time in advance this line will crash. but at the same time i do not want to specify it as it will change.
One could tell me to instenciate this matrix A AFTER changing my time, like
t = 3;
A = [1 -t; 2 t];
but I actually want this time dependant matrix to be a user input ! Thus i'll have the matrix A before anything else in my program.
using the symbolic toolbox is a way but a really slow one. indeed :
syms t
A = [1 -t; 2 t];
t = 3;
tic;
eval(A);
toc;
Elapsed time is 0.002917 seconds.
whereas
t = 3;
tic;
[1 -t; 2 t];
toc;
Elapsed time is 0.000014 seconds.
So is there a fast way to do something like that (knowing that i am running on ODE function thus i really need the evaluation to be performed on a reasonable time).
There is the annonymous function possibility as
A = @(t) [1 -t; 2 t];
t = 3;
tic; A(t); toc
Elapsed time is 0.000233 seconds.
Which seems to be the in-between solution, but can such a function be passed as an argument to a function?
My idea was to create a unassigned variable t and then create my variable A then re-evaluate the compiled version of the variable A, but i don't even know if this is a possible/doable solution
Answers (2)
Oleg Komarov
on 21 Apr 2011
The handle solution:
A = @(t) [1 -t; 2 t];
B = @(x) A(x)
B(3)
Walter Roberson
on 21 Apr 2011
0 votes
If you use the symbolic solution, instead of using eval(A) you should use subs(A) or (more likely) double(subs(A))
3 Comments
Oleg Komarov
on 21 Apr 2011
Just subs is enough but somehow the handle solution is faster on my pc, Win32 r2010b
Walter Roberson
on 21 Apr 2011
subs() would give back a symbolic number; double() is needed to convert it to double precision to be on equal terms with the handle approach.
Oleg Komarov
on 22 Apr 2011
That's what I expected too, but with r2010b I get:
syms t
A = [1 -t; 2 t];
subs(A,3)
isnumeric(ans) % 1
This question is closed.
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!