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

조회 수: 8 (최근 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 CenterFile Exchange에서 Multidimensional Arrays에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by