How to use if, else conditional loop on anonymous function handle?

조회 수: 22 (최근 30일)
hello_world
hello_world 2018년 8월 3일
답변: Albert Fan 2018년 8월 3일
For the following example, given at https://www.mathworks.com/help/stats/evalclusters.html:
eva = evalclusters(meas, 'kmeans', 'CalinskiHarabasz', 'klist',[1:6])
Now, in the following example we use anonymous function handle:
load fisheriris
myfunc = @(X,K)(kmeans(X, K, 'emptyaction','singleton', 'replicate',5));
eva = evalclusters(meas, myfunc, 'CalinskiHarabasz', 'klist',[1:6])
kmeans returns indices, cluster center location, etc. I will like to put an if condition on myfunc before I pass it eva. So if other words, if the given condition fails, I will not like to run evalclusters.
  댓글 수: 4
Albert Fan
Albert Fan 2018년 8월 3일
I don't quite understand you idea. The optimal number of clusters is determined by the evaluation object, and the function handle you fed in is just a clustering algorithm and that algorithm shouldn't be dependent on the optimal number of clusters. So what are you trying to achieve here?
hello_world
hello_world 2018년 8월 3일
@Albert Fan: I have modified the language of my question.

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

채택된 답변

Albert Fan
Albert Fan 2018년 8월 3일
First of all, you cannot add a complex if statement in an anonymous function. The workaround is similar to what Adam has mentioned, is that you can create a regular function and pass the function handle in. for example:
eva = evalclusters(meas, @myfunc, 'CalinskiHarabasz', 'klist',[1:6])
function myfunc
% code
if condition
%do stuff
end
end
Additionally, the optimal cluster number is the result of evalclusters, which means you should not use that number as a condition of the clustering algorithm to stop execution. Otherwise, I personally do not know a way to stop evalcluster inside myfunc. However, if you just want to play with numbers, you can call exit() to stop the entire program. If you still want to execute something after evalclusters, then you could set a global variable and when you meet the condition, you set the variable to true and in mufunc, if that variable is true, do nothing and return. But that is rather complex and not a very good practice.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Quadratic Programming and Cone Programming에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by