フィルターのクリア

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

3 ビュー (過去 30 日間)
Mikel Gonzalez Bribiesca
Mikel Gonzalez Bribiesca 2022 年 11 月 19 日
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 件のコメント
Mikel Gonzalez Bribiesca
Mikel Gonzalez Bribiesca 2022 年 11 月 24 日
Thank you, this worked very well with relative fast speed

サインインしてコメントする。

その他の回答 (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 Center および File ExchangeLoops 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