필터 지우기
필터 지우기

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

조회 수: 2 (최근 30일)
Abdalla Khan
Abdalla Khan 2019년 6월 16일
댓글: Jan 2019년 6월 17일
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.
Jan
Jan 2019년 6월 17일
@Guillaume: Of course, my idea of the histogram was too powerful already.

댓글을 달려면 로그인하십시오.

답변 (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에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by