将函数的单元格数组应用于值 [英] Apply a cell array of functions to a value

查看:59
本文介绍了将函数的单元格数组应用于值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我定义了一个包含值和函数的单元格数组:

I define a cell array that contains values and functions:

>> A = {1, 2, 3; @(x) x+5, @(x) x+10, 5}

A = 

    [    1]    [     2]    [3]
    @(x)x+5    @(x)x+10    [5]

有人知道如何将此单元格数组应用于值吗?例如,当x = 2时,应用程序返回另一个单元格数组:

Does anyone know how to apply this cell array to a value? For instance, when x = 2, the application returns another cell array:

    [ 1]    [     2]    [3]
    [ 7]    [    12]    [5] 

推荐答案

将常量定义为函数:

A = {@(x)1, @(x)2, @(x)3; @(x) x+5, @(x) x+10, @(x)5}

现在使用cellfun:

k = 2;
cellfun(@(x)x(k),A)

还请注意,如果要一次应用多个k值(例如k = 1:5),则需要将A中的常量函数从此形式@(x) n编辑为类似@(x) n*ones(size(x))的内容,然后将cellfun调用更改为:

Also note that if you want to apply multiple k values at once (e.g. k = 1:5) you will need to edit your constant functions in A from this form @(x) n to something like @(x) n*ones(size(x)) and then change the cellfun call to:

cellfun(@(x)x(k),A, 'uni',0)


要从您的评论中回答问题:


To answer the question from your comments:

是否可以在单元格数组中引用函数中的其他单元格? 例如,我们可以定义类似A = {@(x)1, @(x)2, the 1st cell + the 2nd cell, @(x)4}的东西吗?

is it possible to refer to other cells in a function in a cell array? For instance, can we define something like A = {@(x)1, @(x)2, the 1st cell + the 2nd cell, @(x)4}?

您定义A如下:

A = {@(x)1, @(x)2, @(x)(A{1}(x)+A{2}(x)), @(x)4}

这篇关于将函数的单元格数组应用于值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆