Info

This question is closed. Reopen it to edit or answer.

Inserting a randomized array into a for loop

1 view (last 30 days)
Justin Brangiforte
Justin Brangiforte on 29 May 2020
Closed: MATLAB Answer Bot on 20 Aug 2021
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 Comment
KSSV
KSSV on 29 May 2020
What exactly you are trying? Can you show us the expected output?

Answers (1)

Adam Danz
Adam Danz on 29 May 2020
Edited: Adam Danz on 2 Jun 2020
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.

Products


Release

R2019a

Community Treasure Hunt

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

Start Hunting!