Adding value from structure into a vector after each iteration of a for loop.
1 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(1 个)
James Tursa
2022-8-30
编辑:James Tursa
2022-8-30
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.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!