Filter löschen
Filter löschen

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

2 Ansichten (letzte 30 Tage)
Abdalla Khan
Abdalla Khan am 16 Jun. 2019
Kommentiert: Jan am 17 Jun. 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 Kommentare
Guillaume
Guillaume am 17 Jun. 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 am 17 Jun. 2019
@Guillaume: Of course, my idea of the histogram was too powerful already.

Melden Sie sich an, um zu kommentieren.

Antworten (1)

Krishna Anne
Krishna Anne am 17 Jun. 2019
Bearbeitet: Guillaume am 17 Jun. 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 Kommentare
Guillaume
Guillaume am 17 Jun. 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 am 17 Jun. 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. :)

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by