How to save/store/recuparate data from inside a nested loop.
1 次查看(过去 30 天)
显示 更早的评论
So basically a have a nested loop in the following form:
... %Stuff up here
for X=1:N_aoa
initial=[0;aoa(X);0;0];
Y=[initial,zeros(4,N)];
for n=1:N
... %Stuff happens here and I calculate several values "Y"
end
[val,idx]=max(Y, [], 2);
Mat=[aoa(X),val(1),val(2)]
end
Mat %This will only print the last stored value of Mat, which is when X=N_aoa
%Since i'll have lots of values my idea was to do again max but for Mat.
As you can se the problem is that I make 2 evaluations, the inner loop evaluates for a range of 1 to N, while the outer loop is for different values of the intial vector state "initial", basically im varying the second value of [0;aoa(X);0;0], calculating my state in the inner loop and finally I want to calculate the maximum value corresponding to that initial state aoa(X) for the entire range of 1:N, however I dont know how to store since it will be erased once X changes...
0 个评论
回答(2 个)
Sulaymon Eshkabilov
2021-11-11
This can be done:
for X=1:N_aoa
initial=[0;aoa(X);0;0];
Y=[initial,zeros(4,N)];
for n=1:N
... %Stuff happens here and I calculate several values "Y"
end
[val,idx]=max(Y, [], 2);
Mat(X,:)=[aoa(X),val(1),val(2)]; % In a Matrix form
end
Or in a cell array form:
for X=1:N_aoa
initial=[0;aoa(X);0;0];
Y=[initial,zeros(4,N)];
for n=1:N
... %Stuff happens here and I calculate several values "Y"
end
[val,idx]=max(Y, [], 2);
Mat{X}=[aoa(X),val(1),val(2)]; % In a cell array form
end
0 个评论
Bjorn Gustavsson
2021-11-11
This should be simple enough if you do something like this:
Y_best = zeros(n_something,N_aoa); % Not clear to me what your Y contains
for X=1:N_aoa
initial=[0;aoa(X);0;0];
Y=[initial,zeros(4,N)];
best_val = -inf; % threshold-value for best "Y"
for n=1:N
... %Stuff happens here and I calculate several values "Y"
if you_maximizing_variable_val > best_val
best_val = you_maximizing_variable_val;
Y_best(1:numel(Y_current),X) = Y_current; % save away the best values from whatever
end
end
[val,idx]=max(Y, [], 2);
Mat=[aoa(X),val(1),val(2)]
end
Something like that should solve this type of problem.
HTH
0 个评论
另请参阅
类别
在 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!