How to save multiple varibles from the function into the workspace?
25 views (last 30 days)
Show older comments
Hello,
I have got a Matlab function where I solve a system of differential equations with the ode45 function. Everything works fine, but... there is a variable (we can call it H) which is randomly generated with every calculation step (H=rand(1)). That means H changes its value aprox. 15 000 times during calculation (this number can change). What I want is to save H into the array located in the base workspace of Matlab - to have a matrix (vector) with size 15 000x1 for following use. It's not a problem for me to transfer one variable from the function to the workspace (with assignin or putvar function), but I dont know how to transfer many variables and put them into one array.
I have also an idea to save each of H values to the *.mat file and than load all of them into the workspace. Is this somehow possible?
Thank you.
0 Comments
Answers (2)
Amit
on 22 Jan 2014
A possible suggestion (Disclaimer: I have never done it)
If you have some estimate how many times the functions gets called in ODE45, then great. Like you mentioned, lets say its ~15000 times. Now,
N = 15000*1.1; % 10% margin
global rand_gen count;
rand_gen = rand(N,1);
count = 1;
In the function you're calling the random number, define
global rand_gen count;
H = rand_gen(count,1);
count = count + 1;
The idea is to make the random stream and a flag for location global. This way the function can access these values and you'll have them stored as well in workspace.
6 Comments
Amit
on 23 Jan 2014
Also, this function can not take jumps for integration as in every time step things are changing. So ODE45 will have to call this many many time even for small time range.
I am attaching a result from my integration and you suggest if this is something what you expect?

AJ von Alt
on 22 Jan 2014
You can return multiple variables from a function using the function definition syntax:
function [ out1 , out2 , out3 ] = myFunction ( input1 )
out1 = 1;
out2 = 2;
out3 = 3;
You then call the function with the syntax:
[ A, B, C] = myFunction ( input1 )
The outputs out1, out2, and out3 will be stored in A, B, and C respectively.
You can save a single function to a .mat file using the save command followed by the filename and a string containing variable name.
save('myfile.mat','A')
Example:
% save A to myfile.mat
save('myfile.mat','A')
% remove A from the workspace
clear A
% look for A in the work space
whos A
% nothing is returned because A was cleared
% load myfile.mat into the work space
load('myfile.mat')
% check for A in the work space
whos A
% now we see A again
Name Size Bytes Class Attributes
A 1x1 8 double
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!