Filter löschen
Filter löschen

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

3 Ansichten (letzte 30 Tage)
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

Akzeptierte Antwort

Walter Roberson
Walter Roberson am 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) = [];

Weitere Antworten (1)

VBBV
VBBV am 19 Nov. 2022
K = setdiff(randi([1 N]),[k]);
  1 Kommentar
VBBV
VBBV am 20 Nov. 2022
Bearbeitet: VBBV am 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]);

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Produkte


Version

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by