Matlab function to know the number of times element Y exists in array X

2 次查看(过去 30 天)
How to write a ML function which accepts from the user an Array X and a value Y and returns the number of times the element Y exists in X
  3 个评论
Guillaume
Guillaume 2019-6-17
Sounds like the count is only required for one value, not every unique element of X, so it's even easier to obtain than an histogram (i.e. a grand total of 9 characters are needed, not counting the assignment to a variable).
It does indeed sound like homework.

请先登录,再进行评论。

回答(1 个)

Krishna Anne
Krishna Anne 2019-6-17
编辑:Guillaume 2019-6-17
See if this is what you are looking for, you may improve it as per your specific needs
prompt = 'Enter the array X ';
X = input(prompt);
prompt = 'Enter the Value Y ';
Y = input(prompt);
CNT=0;
IDX = ismember(X,Y);
for i=1:size(IDX')
if(IDX(i)== 1)
CNT = CNT+1;
end
end
disp('Number of times Y exists in X is '); disp(CNT);
  2 个评论
Guillaume
Guillaume 2019-6-17
Personally, I think you should let the OP figure out the solution on their own. Note that the solution can be a lot simpler than what you have done.
  • Why do you transpose IDX just to know how many elements there are in it? (hint: if you are using size you can tell it to return the size of a particular dimension. There are also functions that directly return the number of elements in a vector)
  • Hint: compare count to the sum (or nnz) of IDX. That should tell you something about the need for the loop.
  • Hint: compare the result of ismember to X == Y.
Krishna Anne
Krishna Anne 2019-6-17
I agree, that's why I said to improve it, this one still does not work universally (2D arrays for instance) so there is lot of room to still brainstorm and improve. Only reason to give this is that I generally see answers after many months which is not very helpful.
Thanks for your suggestion anyway, I know that there are thousands of non-trivial possibilities in MATLAB world to solve things and many times there are ready made functions. The real picture is either to improve one's knowledge on number of availble functions (vocabulary) or to choose to program it on their own. Either of these choices would not need a posting of question here. :)

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Data Distribution Plots 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by