Reputation: 1571
I want to store values of different matrix/vector sizes for each loop that my algorithm is performing. My MWE is as follows:
for n1=1:T
a1=f1(n1) % Some expression which depends on n1
% a1 is just a parameter value
for n2=1:T
a2=f2(n2) % Some expression which depends on n2
% a2 is just a parameter value
while d<1
algorithm=F(a1,a2,) % my algorithm depends on these parameter values
end
% In this step I want remember the combination of parameters and store some results
v1= [a1 a2] % I store the combination of parameters used in the while loop
[A,B,C]=somefunction() % some results given inputs from the while loop
% A,B,C are matrices **of Different sizes**
v2 = [ 4x1 4x1 4x1] % I store some column vectors
% What I basically want to do is
% to remember and SEE in some MATLAB convenient form the following:
% 1. for this combination of parameters in v1
% 2. I got A B C matrices and the matrix v2
end
end
Can one help me how I can do this as efficiently as possible ? Ideally I want to be store the names of of all parameter values and matrices for every time the for loop is executed, but I don;t know whether this is possible in MATLAB.
Upvotes: 0
Views: 191
Reputation: 1025
Depending what you're trying to look at, a cell structure will allow you to view different array sizes/data-types in one structure pretty conveniently.
results = {};
for n1=1:T
for n2=1:T
...
results{n1,n2,1} = a1
results{n1,n2,2} = a2
results{n1,n2,3} = v1
results{n1,n2,4} = v2
results{n1,n2,5} = A
results{n1,n2,6} = B
results{n1,n2,7} = C
end
end
The dynamic struct.field approach mentioned here also works well. You have to decide whether a pseudo-array approach (cell) or tree approach (struct.field) works best for accessing/viewing/storing your data.
Upvotes: 1
Reputation: 2919
Consider using dynamic field references in a structure. What this will allow you to do is create an ouput structure, with the results and the inputs for a given run in the loop. Adapting the idea to your code.
for n2=1:maxruns
% Same code as above.
AlgorithmOutput.((strcat('Run',int2str(n2))).input.A1=a1
AlgorithmOutput.((strcat('Run',int2str(n2))).input.A2=a2
% this will store your inputs in something like AlgorithmOutput.Run1.input
AlgorithmOutput.((strcat('Run',int2str(n2))).output.V1=v1;
AlgorithmOutput.((strcat('Run',int2str(n2))).output.V2=v2;
% this will store your inputs in something like AlgorithmOutput.Run1.output
end
Things to note here, you will need to make sure that you start the dynamic reference with a letter and not a number (matlab naming rules). You will also need to use something like fields(AlogrithmOutput)
which will return a cell array in this case of all the runs which you can then subsequently iterate over.
While this will cause some issues if you have very deep and complex inputs and outputs, this should allow an intuitive way to access for the inputs/outputs of any given run through syntax such as AlogrithmOutput.Run5.input.A1
etc.
Upvotes: 2