How to remove a value from a vector in a for loop?

3 次查看(过去 30 天)
Basically I am working with the variables k and l.
Originally I created a vector of N values and make a for loop from 1 to N.
In the for loop I put 2 randi functions that pick 2 values from 1 to N. The first one being k and the second one being l.
But now I want to exlude from the possibilities the to be picked the values that have already been picked. So no value is picked twice.
I tried using setdiff, yet I fail at implementing it.
This is what I tried doing.
for i = 1:1:N
k = randi([1 N]);
K = setdiff([1 N],[k]);
l = randi([1 N]);
L = setdiff([1 N],[l]);
DS = randi([-1 1]);
if DS == 1 && A(1,l) - unit > 0
A(1,k) = A(1,k) + unit;
A(1,l) = A(1,l) - unit;
elseif DS == -1 && A(1,k) - unit > 0
A(1,k) = A(1,k) - unit;
A(1,l) = A(1,l) + unit;
end
How would someone implement the idea?
Thank you

采纳的回答

Walter Roberson
Walter Roberson 2022-11-19
candidates = 1:N;
kidx = randi(numel(candidates));
k = candidates(kidx);
candidates(kidx) = [];
lidx = randi(numel(candidates));
l = candidates(lidx);
candidates(lidx) = [];
Or....
klidz = randperm(numel(candidates), 2);
k = candidates(klidx(1));
l = candidates(klidx(2));
candidates(klidx) = [];

更多回答(1 个)

VBBV
VBBV 2022-11-19
K = setdiff(randi([1 N]),[k]);
  1 个评论
VBBV
VBBV 2022-11-20
编辑:VBBV 2022-11-20
you can also try this
k = randi([1 N])
K = setdiff(randi([1 N],1,i),[k])
L = setdiff(randi([1 N],1,i),[l]);
or do you mean this
k = randi([1 N])
K = setdiff(([1:N],[k]); % use values from 1:N instead of just 1 and N
L = setdiff(([1:N],[l]);

请先登录,再进行评论。

类别

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

产品


版本

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by