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

1 visualización (últimos 30 días)
Cuoa Um
Cuoa Um el 11 de Nov. de 2021
Respondida: Bjorn Gustavsson el 11 de Nov. de 2021
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...

Respuestas (2)

Sulaymon Eshkabilov
Sulaymon Eshkabilov el 11 de Nov. de 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

Bjorn Gustavsson
Bjorn Gustavsson el 11 de Nov. de 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

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Productos


Versión

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by