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

3 views (last 30 days)
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

Accepted Answer

Walter Roberson
Walter Roberson on 19 Nov 2022
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) = [];

More Answers (1)

VBBV
VBBV on 19 Nov 2022
K = setdiff(randi([1 N]),[k]);
  1 Comment
VBBV
VBBV on 20 Nov 2022
Edited: VBBV on 20 Nov 2022
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]);

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products


Release

R2021a

Community Treasure Hunt

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

Start Hunting!