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

1 次查看(过去 30 天)
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 个评论
Rik
Rik 2018-8-10
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.
Prabha Kumaresan
Prabha Kumaresan 2018-8-10
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.

请先登录,再进行评论。

采纳的回答

Rik
Rik 2018-8-10
编辑:Rik 2018-8-10
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 个评论
Rik
Rik 2018-8-14
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

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by