Info
此问题已关闭。 请重新打开它进行编辑或回答。
Inserting a randomized array into a for loop
1 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(1 个)
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.
0 个评论
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!