How to save/store/recuparate data from inside a nested loop.

조회 수: 1(최근 30일)
Cuoa Um
Cuoa Um 2021년 11월 11일
답변: Bjorn Gustavsson 2021년 11월 11일
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...

답변(2개)

Sulaymon Eshkabilov
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

Bjorn Gustavsson
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

Community Treasure Hunt

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

Start Hunting!

Translated by