How to save/store/recuparate data from inside a nested loop.
1 view (last 30 days)
Show older comments
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 Comments
Answers (2)
Sulaymon Eshkabilov
on 11 Nov 2021
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 Comments
Bjorn Gustavsson
on 11 Nov 2021
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 Comments
See Also
Categories
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!