gpt4 book ai didi

matlab - 将函数元胞数组应用于值

转载 作者:太空宇宙 更新时间:2023-11-03 19:53:23 26 4
gpt4 key购买 nike

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

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

A =

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

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

    [ 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 调用:

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

根据您的评论回答问题:

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}

关于matlab - 将函数元胞数组应用于值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33144403/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com