Create a function that uses indexing
显示 更早的评论
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 个评论
Dyuman Joshi
2024-3-7
"% but how do you select a single element number that is a random integer from 1 to N?
Refer to the documentation of randi. Whenver you have any question(s) about a function, it is always best to refer to its documentation.
% How do you then take that random element number and return Value as the actual number saved in that
% random location in vector vec?"
Use indexing.
Spaceman
2024-3-8
Dyuman Joshi
2024-3-8
编辑:Dyuman Joshi
2024-3-8
"My Solution: Does this make sense?"
It does,
"%% I just want to make sure it makes sense to people with vastly more experience in MATLAB environment than myself."
but (imo) you should not worry about this. You should focus on whether you know and understand what's going on.
Also, try incorporating comments in your code, so that you have an idea what each line does. And it will be helpful to others and to you for future reference.
In any case, (if ever in doubt) you should test your code against multiple inputs, and see if the outputs are as expected or not.
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.
Spaceman
2024-3-9
采纳的回答
更多回答(0 个)
类别
在 帮助中心 和 File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!