Adding value from structure into a vector after each iteration of a for loop.
6 views (last 30 days)
Show older comments
Hi,
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]
end
end
end
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!
0 Comments
Answers (1)
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.
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!