matlab 常量匿名函数只返回一个值而不是数组 [英] matlab constant anonymous function returns only one value instead of an array

查看:35
本文介绍了matlab 常量匿名函数只返回一个值而不是数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在网上搜索了几个上午,但一无所获,希望能帮到您.

I've been searching the net for a couple of mornings and found nothing, hope you can help.

我有一个这样的匿名函数

I have an anonymous function like this

f = @(x,y) [sin(2*pi*x).*cos(2*pi*y), cos(2*pi*x).*sin(2*pi*y)];

需要在一组点上进行评估,例如

that needs to be evaluated on an array of points, something like

x = 0:0.1:1;
y = 0:0.1:1;
w = f(x',y');

现在,在上面的例子中一切正常,结果 w 是一个 11x2 矩阵,每行都有正确的值 f(x(i), y(i)).当我将函数更改为具有常量值时,问题就出现了:

Now, in the above example everything works fine, the result w is a 11x2 matrix with in each row the correct value f(x(i), y(i)). The problem comes when I change my function to have constant values:

f = @(x,y) [0, 1];

现在,即使像以前一样输入数组,我也只能得到一个 1x2 的数组,例如 w = [0,1];当然,我希望拥有与以前相同的结构,即 11x2 矩阵.

Now, even with array inputs like before, I only get out a 1x2 array like w = [0,1]; while of course I want to have the same structure as before, i.e. a 11x2 matrix.

我不知道为什么 Matlab 这样做...

I have no idea why Matlab is doing this...

编辑 1对不起,我认为我在原始问题中写的内容很清楚,但我看到你们中的一些人在问,所以这里澄清一下:我想要再次拥有一个 11x2 矩阵,因为我正在为函数提供数组有 11 个元素.这意味着我希望有一个与第一个示例完全相同的输出,只是其中的值发生了变化:一个有 11 行和 2 列的矩阵,第一列中只有值 0,第二列中只有值 1,因为对于所有x(i) 和 y(i) 答案应该是向量 [0,1].这意味着我希望有:

EDIT 1 Sorry, I thought it was pretty clear from what I wrote in the original question, but I see some of you asking, so here is a clarification: what I want is to have again a 11x2 matrix, since I am feeding the function with arrays with 11 elements. This means I expect to have an output exactly like in the first example, just with changed values in it: a matrix with 11 rows and 2 columns, with only values 0 in the first column and only values 1 in the second, since for all x(i) and y(i) the answer should be the vector [0,1]. It means I expect to have:

w = [0 1
     0 1
     0 1
     ...
     0 1]

对我来说似乎很自然...

seems pretty natural to me...

推荐答案

您正在定义一个函数 f = @(x,y) [0, 1]; ,它具有输入参数 x,y 和输出 [0,1].您还期望发生什么?

You are defining a function f = @(x,y) [0, 1]; which has the input parameters x,y and the output [0,1]. What else do you expect to happen?

更新:

这应该与您的描述相符:

This should match your description:

g=@(x,y)[zeros(size(x)),ones(size(y))]
g(x',y')

这篇关于matlab 常量匿名函数只返回一个值而不是数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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