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

11 ビュー (過去 30 日間)
Kylenino Espinas
Kylenino Espinas 2020 年 10 月 9 日
回答済み: Steven Lord 2020 年 10 月 9 日
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.

回答 (1 件)

Steven Lord
Steven Lord 2020 年 10 月 9 日
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.

カテゴリ

Help Center および File ExchangeMultidimensional Arrays についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by