How to save multiple varibles from the function into the workspace?
31 views (last 30 days)
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?
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.
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 A to myfile.mat
% remove A from the workspace
% look for A in the work space
% nothing is returned because A was cleared
% load myfile.mat into the work space
% check for A in the work space
% now we see A again
Name Size Bytes Class Attributes
A 1x1 8 double