MATLAB Answers

0

Could anyone help me to solve the issue for the following code

Asked by Prabha Kumaresan on 10 Aug 2018 at 5:35
Latest activity Commented on by Prabha Kumaresan on 15 Aug 2018 at 4:49

code:

A=1:12
while ~isempty(A)
B=ceil(sqrt(randi([numel(A)])))
C=A(randsample(length(A),B))
[~,idx]=find(ismember(A,C))
A(idx)=[]
end

The above code executes. but the outcome of B need to be increased subsequently,which means for first time B=1,next B=2,B=3 until B does not satisfy the subsequent condition.When b does not satisfy the subsequent condition,then B needs to start second time from beginning in such a way again B=1,B=2,B=3.In second time as A is 12,B can be 1 but B cannot be 2,so B needs to be treated again as 1.Similarly i need to run the code when i Change the value of A to 24,36 and so on.Could anyone help me to solve the issue.

  2 Comments

I have no idea what you mean in your description, so please explain it a bit more step by step. It sounds like you want to have B increment on each iteration. If you want that, then you shouldn't be using random generation and you should remove elements in A.

yes. you are correct.B needs to get incremented on each iteration. When A=12,till 4 iterations B can take corresponding values from A on each increment.But for 5th iteration it is not possible to take 5 values from A as the remaining number of values in A are 2. So once again the iteration needs to start from the beginning.As a result for 5th iteration B needs to take one value from A.For 6th iteration B needs to take 2 values from A,as there are only one value is left,so for 6th iteration B once again needs to take the last value from A.

Yes i should not use random generation.Could you please help me how to overcome it.

Sign in to comment.

1 Answer

Answer by Rik Wisselink
on 10 Aug 2018 at 8:28
Edited by Rik Wisselink
on 10 Aug 2018 at 8:50
 Accepted Answer

I think I understand what you mean. If I do, then the code below should work for you.

A=1:12;
B=0;
while ~isempty(A)
    B=B+1;
    if B>numel(A),B=1;end
    C=A(randsample(length(A),B));
    [~,idx]=find(ismember(A,C));
    A(idx)=[];
end

  26 Comments

s.but how to get the result with respect to indexing

You mean you want to have those values in a loop, just like with the while-loop?

A=1:12;
C_matrix=reshape(A,[],3);
C_matrix(:,end)=C_matrix(end:-1:1,end);
for k=1:size(C_matrix,1)
    C=C_matrix(k,:)
end

Sign in to comment.