Matlab函数句柄小测

其类似于C/C++中函数名或者函数的取地址操作,在C/C++中函数的作为参数的传递,可以通过函数名func或者&func的形式作为参数。

matlab code:

data=load('../train_task_data.mat','train_task_data');
train_task_data=data.train_task_data;

opt.lossType='square'; % hinge , square

if strcmp(opt.lossType,'hinge')
    grad=compute_gradient2(@hinge,train_task_data);
elseif strcmp(opt.lossType,'square')
    grad=compute_gradient2(@square,train_task_data);
end

disp('over...');

function grad=compute_gradient2(func,train_task_data)
%do some common work
%..........
% call
grad=func(train_task_data);
end

c++ code

#include "stdafx.h"
#include<iostream>
using namespace std;

float hinge(float *train_task_data)
{
    cout << "hinge function" << endl;
    return 0;
}

float square(float *train_task_data)
{
    cout << "square function" << endl;
    return 1;
}

float compute_gradient2(float loss_func(float*), float *train_task_data)
{
    float grad=loss_func(train_task_data);
    return grad;
}

int main()
{
    float train_task_data[5] = { 1,2,3,4,5 };
    float grad1 = compute_gradient2(hinge, train_task_data);
    //或者
    float grad2 = compute_gradient2(&hinge, train_task_data);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值