Azzera filtri
Azzera filtri

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

3 visualizzazioni (ultimi 30 giorni)
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

Risposta accettata

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

Più risposte (1)

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

Accedi per commentare.

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Prodotti


Release

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by