Info

この質問は閉じられています。 編集または回答するには再度開いてください。

Inserting a randomized array into a for loop

1 回表示 (過去 30 日間)
Justin Brangiforte
Justin Brangiforte 2020 年 5 月 29 日
閉鎖済み: MATLAB Answer Bot 2021 年 8 月 20 日
Hey guys and girls I have been trying to insert an array that has been randomized by the randi and randperm command built into MATLAB. I then want to take each number in the array and run it through a series of if and elseif statements and then output that to a resutlant array. Thanks for the help
XA = [5 6 2 6 5 3 3 5 3 3 6 5];
for i = XA,length(XA)
if XA == 6
Y = randi([2,4],1);
elseif XA == 5
Y = randi([2,4],1);
elseif XA == 4
Y = randi([5,6],1);
elseif XA == 3
Y = randi([5,6],1);
elseif XA == 2
Y = randi([5,6],1);
end
end
  1 件のコメント
KSSV
KSSV 2020 年 5 月 29 日
What exactly you are trying? Can you show us the expected output?

回答 (1 件)

Adam Danz
Adam Danz 2020 年 5 月 29 日
編集済み: Adam Danz 2020 年 6 月 2 日
No need for the conditional statements. Use indexing instead. Indexing is the life and blood of Matlab.
XA = [5 6 2 6 5 3 3 5 3 3 6 5];
y = nan(size(XA));
y(XA==6) = randi([2,4],1,sum(XA==6));
y(XA==5) = randi([2,4],1,sum(XA==5));
y(XA==4) = randi([5,6],1,sum(XA==4));
y(XA==3) = randi([5,6],1,sum(XA==3));
y(XA==2) = randi([2,4],1,sum(XA==2));
The lines above could be simplified further since many of them use the same randi ranges but this is a simpler way to see what's going on.

製品


リリース

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by