# Storing a loop index value in a dynamic array?

39 views (last 30 days)
Craig Atkinson on 20 Feb 2021
Commented: J. Alex Lee on 24 Feb 2021
This really is a made-up example computationally, I'm not sure if those random constraints are ever satisfied or not, but it still illustrates what I am trying to do. Essentially, my program uses ndgrid to find all of the values that meet the constraints that I specify. One of these values, though, cannot be used with ndgrid because it is used as an input to a function that requires a scalar value. Because of this, I am using the loop to fill the rest of the possible combinations. However, I can no longer keep track of which value of W is correlated with each row in the Locations matrix. It is almost useless for me to even increment W if I don't know which of its values caused an output row that I am interested in. Is there any way to store the current value of W in the last column of the locations matrix, without knowing how many rows are concatenated to the matrix with each iteration? (it changes dynamically in my program, and one increment of W may add 50 rows while another may add 2)
clear
clc
Locations = [];
for W = 0:0.01:1
[X,Y,Z] = ndgrid(1:0.1:1);
F = X.^2 + Y - 3.*Z + W^2;
G = Y.^2 + Z.^4 - 6*W; % random functions
H = X + Y + Z.^3;
idx=(F<=1 & G>=5 & H>=5); % random constraints
Locations = unique([Locations; X(idx),Y(idx),Z(idx)],'rows');
% I want the value of W that was used for the calculations
% that the indices reference
% Locations = unique([Locations; X(idx),Y(idx),Z(idx),W],'rows');
end
J. Alex Lee on 24 Feb 2021
I'm still not sure I understand...but on thinking about it more if you literally want to just do what you have in your sample code and create a vector of height the same height as the final Locations array that tracks which W you are appending locations from, then you can use ismember to test for collision between your current list of coordinates and your growing history:
CurLoc = [X(idx),Y(idx),Z(idx)]
Locations = [Locations ; LocAppend]
WList = [WList ; W .* ones(size(LocAppend,1),1)]
But I guess you will always lose information about other values of W that satisfied your criteria

J. Alex Lee on 20 Feb 2021
Without trying to get into the weeds of your need, did you know that "unique" can additionally output indices into each argument, and would tha thelp you? Per the help screen:
[C,IA,IC] = unique(A,'rows') also returns index vectors IA and IC such
that C = A(IA,:) and A = C(IC,:).
Craig Atkinson on 20 Feb 2021
Interesting, I actually didn't know that I might be able to use that for other portions of my program. Unfortunately I still need to figure out a way a way to track that looping value

R2020b

### Community Treasure Hunt

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

Start Hunting!

Translated by