Randomly generate a vector containing integers. Extract items from odd positions using a single command line
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Dacian Andrei Firca
el 3 de Mzo. de 2022
Comentada: Dacian Andrei Firca
el 16 de Mzo. de 2022
Hi guys. How can i randomly generate a vector containing integers and extract items from odd positions using a single command line?
Thank you!
0 comentarios
Respuesta aceptada
Konrad
el 3 de Mzo. de 2022
Editada: Konrad
el 3 de Mzo. de 2022
Hi Dacian,
indexing an expression (e.g. randi(100,10,1)(1:2:9)) is not possible in Matlab.
Here is a workaround using groupsummary() that generates 10 random integers between 1 and 100 and returns the numbers at odd indices:
groupsummary(randi(100,10,1), reshape(repmat(1:2:10,2,1),[],1), @(x)x(1))
You can also put this into an anonymous function (although if creating an anonymous function first is an option, there would be much simpler solutions, of course):
randi_oddIdx = @(imax,n)groupsummary(randi(imax,n,1), reshape(repmat(1:2:n,2,1),[],1), @(x)x(1))
Note that this only works for even numbers of random integers!
Best, Konrad
Más respuestas (1)
Walter Roberson
el 3 de Mzo. de 2022
struct('d',randi(100,1,1)).d(1:2:end)
Does not require that the number of values is even.
Seems pointless to me unless you are carefully controlling the random seed. Just wastes time and is unclear. The numbers are not more random by taking every second one instead of all of them.
Ver también
Categorías
Más información sobre Creating and Concatenating Matrices en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!