Storing a loop index value in a dynamic array?
6 次查看(过去 30 天)
显示 更早的评论
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
3 个评论
J. Alex Lee
2021-2-24
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)]
mask = ismember(CurLoc,Locations)
LocAppend = CurLoc(~mask,:)
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
2021-2-20
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,:).
更多回答(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!