How can I keep just the arrays with 2 is before 3 after random swap 2 numbers.

3 ビュー (過去 30 日間)
Hang Vu
Hang Vu 2019 年 4 月 17 日
コメント済み: Jan 2019 年 4 月 19 日
with: s=[1,2,3,4,5];
  2 件のコメント
madhan ravi
madhan ravi 2019 年 4 月 17 日
Show how your output should look like.
Hang Vu
Hang Vu 2019 年 4 月 17 日
Thanks for response! the output should be s=[1,4,2,3,5] or [2,4,1,5,3] for example. just to make sure 2 before 3

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

採用された回答

Jan
Jan 2019 年 4 月 17 日
編集済み: Jan 2019 年 4 月 17 日
s = [1,2,3,4,5];
s = s(randperm(numel(s))); % Random permutation?
% Or swap 2 elements:
index = randperm(numel(s), 2);
s(index) = s(flip(index));
s(s == 2 | s == 3) = [2, 3]; % Re-order the elements 2 and 3
  4 件のコメント
Hang Vu
Hang Vu 2019 年 4 月 18 日
Thank you for the re order idea! I applied for this:
s=[1,2,3,4,5];
L=size(s,2);
a=randi([1 L-1],1);
b=randi([1 L-1],1);
temp=s(a);
s(a)=s(b);
s(b)=temp
for i=1:5
ind1=find(s(:,:)==2);
ind2=find(s(:,:)==3);
end
if ind1>ind2
s(s == 2 | s == 3) = [2, 3];
s
else
s
end
Jan
Jan 2019 年 4 月 19 日
This is not useful:
for i=1:5
ind1=find(s(:,:)==2);
ind2=find(s(:,:)==3);
end
The body of the loop is calculated 5 times with identical values. You can omit the loop:
ind1=find(s(:,:)==2);
ind2=find(s(:,:)==3);
But you can omit this test completely. This is sufficient for all cases:
s(s == 2 | s == 3) = [2, 3];
Why do you use L-1 in randi([1 L-1],1) ? I assume you want L instead.

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

その他の回答 (1 件)

Raj
Raj 2019 年 4 月 17 日
Try this:
s=[1,2,3,4,5]
%First random swap
x=randi([1,4],1,1);
if s(x)~=2
s([x x+1])= s([x+1 x]);
else
s([x x-1])=s([x-1 x]);
end
disp('After first random swap s=')
disp(s);
%second random swap
y=randi([1,4],1,1);
if s(y)~=2
s([y y+1])= s([y+1 y]);
else
%Do nothing
end
disp('After second random swap s=')
disp(s);
There may be better and optimized way of doing this also but this also works!

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by