Adding value from structure into a vector after each iteration of a for loop.

2 views (last 30 days)
I'm running an optimization solver program in MATLAB that outputs a structure (Sol) with a particular value in it that I'm interested in (Sol.x). I use a nested for loop to run the solver for 3 different [1 2] vectors (8 different conditions total, two Sol.x values for each iteration). Before running the program, I create the following vector to store the 8 values (xValue) and run the following:
Output = [1, 2];
n = length(Output);
xValue = zeros(1,8);
for i = 1:1:n
for j = 1:1:n
for k = 1:1:n
[proceed with program]
xValue(i,j,k) = [Sol.x]
However, instead of getting my xValue vector filled with the 8 outputs, I instead get a 2 x 8 x 2 double for xValue:
val(:,:,1) =
1.0e-03 *
0.1027 0.1027 0 0 0 0 0 0
0.0836 0.0534 0 0 0 0 0 0
val(:,:,2) =
1.0e-03 *
0.1027 0.1027 0 0 0 0 0 0
0.1027 0.1027 0 0 0 0 0 0
Is it possible to have these 8 values added into xValue as they are computed in the for loop? I'm concerned that if I expand this program to include greater than 3 x [1 2] vectors, I will run into even more difficulty.
Thank you for your help!

Answers (1)

James Tursa
James Tursa on 30 Aug 2022
Edited: James Tursa on 30 Aug 2022
The reason you are getting a 2x8x2 answer is because you start with a 1x8 vector but then assign spots outside of those limits inside your for-loop. Specifically, you assign the xValue(2,2,2) spot, so MATLAB dynamically increases the size of xValue to accomodate that expansion. You need to rewrite your code and consider the dimensions of xValue. E.g., maybe have it as a 2x2x2 to begin with and use your current indexing. Or maybe keep it as 1x8 but alter your indexing.
Maybe you could tell us what the general situation is, and what sizes you are considering for your expanded program.
  1 Comment
Ryan Graham
Ryan Graham on 30 Aug 2022
Thank you very much James, this is helpful. I didn't catch that earlier that indexing concern previously (with I, j, and k). For context, there are three [1 2] vectors which are the boundaries of the problem. Each vector represents a different parameter. Essentially what I'm replicating with these for loops is a 3 factor 2 level DoE (with the optimization program outputting a structure with a value x that I'm trying to store in the xValue vactor). Would you be able to point me in the right direction as to how to store these values? Currently, there are only 3 vectors. But in the future, there could be several hundred.

Sign in to comment.


Find more on Loops and Conditional Statements in Help Center and File Exchange


Community Treasure Hunt

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

Start Hunting!