Create a function that uses indexing
3 ビュー (過去 30 日間)
古いコメントを表示
Given: Create a function called pick_username that will receive an input argument, which is a vector of values. The function will randomly pick one element out of the provided input vector vec and return the value in that element. Remember, your element numbers are integers from 1 to N, where N is the total number of values in the vector.
Find: How do you select a single element number that is a random integer from 1 to N? How do you then take that random element number and return Value as the actual number saved in that random location in vector vec?
Issue: I'm not sure if I am supposed to be using a function that ramdomizes results or just using the randi function.
My Solution: Does this make sense?
%% Thanks to Victor, I think I understand what to do here, I just want
%% to make sure it makes sense to people with vastly more experience in MATLAB environment than myself.
function Value=pick_kweave19(vec)
%length(vec); % This function is used to determine the length of vector,
%but do I even need this line of code if I have the next line as is?
%random_index = randi(length(vec)); % I took this line of code out as it is
%redundant, I assigned Value to the output instead
Value=randi(length(vec))
end
% Code used to call function vec=1:1:100; Value=pick_kweave19(vec)
5 件のコメント
Victor
2024 年 3 月 8 日
"%but do I even need this line of code if I have the next line as is?"
It is not necessary, I just put a separated line there so that you can know how to find the length of the input array.
採用された回答
Victor
2024 年 3 月 7 日
編集済み: Victor
2024 年 3 月 7 日
Here is the full program, it can run in a m-file, if you want the function only, you can spilt it and use it in other m-file. Remember, return 1 thing at a time and if you have any questions, feel free to ask! :D
namearray = {'apple', 'banana', 'orange', 'grape','mango'}; % Create array with string elements
pick_kweave19(namearray)
function Value=pick_kweave19(array)
length(array); % This function is used to determine the length of array
random_index = randi(length(array)) % Choosing a random index in the length of array, add ' ; ' at the
% end if you dont want it to appear on command window
Value=random_index;
%Value=array(random_index); % Uncomment this line if you wish to return
% the value of array at the random index
% Remeber to return 1 thing only at a time!!
end
4 件のコメント
Victor
2024 年 3 月 8 日
You can accept my answer so that if anyone encounters the question like you, they can read my explanation :D
その他の回答 (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!