executing a loop most probably while
1 view (last 30 days)
Show older comments
I have created a function which groups a vast data. Here, for simplicity, I have used 20 data points. group(x,y) creates the required group (g1) and the next 'for' loop removes the elements of this group to create a new dataset. Again the group(x,y) creates the next group(g2) and the initial dataset is modified. I want to create a loop which will execute this till the dataset has zero elements,i.e. all the elements are grouped with group numbers,g1,g2 etc. I have tried to use while loop but I cannot change the group names, hence the error. Any help will be appreciated.
x = gallery('uniformdata',20,1,1);
y = gallery('uniformdata',20,1,1);
group(x,y);
g1=ans
for i=1:length(g1)
x(any(x==g1(i,1),2),:)=[];
y(any(y==g1(i,2),2),:)=[];
end
group(x,y);
g2=ans
for i=1:length(g2)
x(any(x==g2(i,1),2),:)=[];
y(any(y==g2(i,2),2),:)=[];
end
3 Comments
Stephen23
on 16 Jan 2018
@Busy Bee:
- Why do you not return any output from group ?
- Do NOT use ans as a variable name.
- Do not try to magically generate variable names g1, g2, etc:
Just use simpler and much more efficient indexing.
Accepted Answer
Guillaume
on 16 Jan 2018
Edited: Guillaume
on 16 Jan 2018
First, some important notes
group(x, y);
g = ans;
Do not do this! This is just a more complicated and confusing way of simply doing
g = group(x, y);
Secondly, you create x and y as column vectors, but then have
x(any(x == g(i,1), 2), :) = [];
y(any(x == g(i,1), 2), :) = [];
which is designed for x and y matrices. If x and y are indeed vector then the above can be reduced simply to
x(x == g(i, 1)) = [];
y(y == g(i, 2)) = [];
In addition the i loop can be entirely removed, for x, y matrices:
x(any(ismember(x, g(:, 1)), 2)) == [];
y(any(ismember(y, g(:, 2)), 2)) == [];
and for x, y vectors simply:
x(ismember(x, g(:, 1))) = [];
y(ismember(y, g(:, 2))) = [];
Now to answer your question, first do not number variables, see Stephen's comment. Instead create a cell array that can easily be indexed:
x = gallery('uniformdata',20,1,1);
y = gallery('uniformdata',20,1,1);
g = {}; %better variable name required
count = 0;
while ~isempty(x)
count = count + 1;
g{count} = group(x, y);
x(ismember(x, g{count}(:, 1))) = [];
y(ismember(y, g{count}(:, 2))) = [];
end
g{i} is the ith group.
More Answers (0)
See Also
Categories
Find more on Matrix Indexing 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!