Effacer les filtres
Effacer les filtres

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

2 vues (au cours des 30 derniers jours)
Abdalla Khan
Abdalla Khan le 16 Juin 2019
Commenté : Jan le 17 Juin 2019
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 commentaires
Guillaume
Guillaume le 17 Juin 2019
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.
Jan
Jan le 17 Juin 2019
@Guillaume: Of course, my idea of the histogram was too powerful already.

Connectez-vous pour commenter.

Réponses (1)

Krishna Anne
Krishna Anne le 17 Juin 2019
Modifié(e) : Guillaume le 17 Juin 2019
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 commentaires
Guillaume
Guillaume le 17 Juin 2019
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 le 17 Juin 2019
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. :)

Connectez-vous pour commenter.

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by