How do I make the function return values only from the array?

4 visualizaciones (últimos 30 días)
Kylenino Espinas
Kylenino Espinas el 9 de Oct. de 2020
Respondida: Steven Lord el 9 de Oct. de 2020
function [selectedValues] = selectRandom( dataSet, numberSelected )
% selectRandom: Return numSel elements of input array data selected at
% random. Duplicate selections are acceptable.
% Inputs: data - array of input data values
% numSel - number of randomly selected elements to return
% Outputs: selected - array of randomly selected data values
selectedValues = randi(dataSet, 1, numberSelected);
% Choose randomly selected elements for output.
end
selectRandom([ 74, 13, 1, 51, 6 ], 3)
I have tried using length(dataSet) or sorting and then using dataSet(1,end) but the values can only be the ones in the command.

Respuestas (1)

Steven Lord
Steven Lord el 9 de Oct. de 2020
Right now you're generating an integer value between 1 and the first input. That's not what you want to do.
You want to generate an integer value between 1 and the number of elements (numel) of first input and use that integer value as an index.
What you're returning right now is the indices. You want to use the indices inside your function. If I asked you for the fourth card in a shuffled deck of cards, you're not going to give me the number 4 back. You're going to give me (for example) the 7 of clubs by counting down four cards in the deck and handing that card to me.

Categorías

Más información sobre Matrix Indexing en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by