How do I make the function return values only from the array?
4 次查看(过去 30 天)
显示 更早的评论
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.
0 个评论
回答(1 个)
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.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!