Info

La pregunta está cerrada. Vuélvala a abrir para editarla o responderla.

Inserting a randomized array into a for loop

1 visualización (últimos 30 días)
Justin Brangiforte
Justin Brangiforte el 29 de Mayo de 2020
Cerrada: MATLAB Answer Bot el 20 de Ag. de 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 comentario
KSSV
KSSV el 29 de Mayo de 2020
What exactly you are trying? Can you show us the expected output?

Respuestas (1)

Adam Danz
Adam Danz el 29 de Mayo de 2020
Editada: Adam Danz el 2 de Jun. de 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.

Productos


Versión

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by