洛伦(Matlab)的艺术

将想法变成MATLAB

笔记

洛伦(Matlab)的艺术has been retired and will not be updated.

More on expansion: arrayfun

由于似乎对进入的话题有很多兴趣beyond scalar expansion,,,,it seems worth talking about yet some other ways to achieve the same goals. I am very appreciative of the thoughtful comments we've received so far on this topic and I know we will be weighing this input carefully as we design how to move forward.

假设我们想提高所有值Xto all the powers in权力,,,,where bothX权力是矢量,这样:

权力= 1:3; x = (0:.1:.4)';

我们从last blog article,,,,we can achieve this by creating larger intermediate arrays like this, using Tony's trick (used for most of the work inrepmat

X= x(:,ones(size(powers,2),1)) P = powers(ones(size(x,1),1),:)
X= 0 0 0 0.1000 0.1000 0.1000 0.2000 0.2000 0.2000 0.3000 0.3000 0.3000 0.4000 0.4000 0.4000 P = 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3

然后我们准备执行所需的计算:

Q =X。^P
Q = 0 0 0 0.1000 0.0100 0.0010 0.2000 0.0400 0.0080 0.3000 0.3000 0.0900 0.0270 0.4000 0.4000 0.1600 0.0640

但是以2个较大阵列为代价,Xp,,,,that we might not even need going forward.

在MATLAB 7中没有新操作员的情况下,我们今天如何解决此问题而不创建这些临时阵列,而无需使用为了loop? A new feature in R14sp3,arrayfun是一个很好的候选人。这是两种使用相同结果的方法arrayfun,,,,the first iterating calculating results for each value ofX和the second, for each value of权力。我正在利用MATLAB 7中新的匿名函数来定义我要计算的功能,首先是权力,第二,作为Xvalues.

pq = cell2mat(arrayfun(@(p)x。^p,powers,'siformoutput',false));xq = cell2mat(arrayfun(@(x)x。

在继续之前,让我们确保我们得到正确的答案!

quequal(xq,pq,q)ans = 1

Now that we've taken care of checking for correctness, let's decipher what the statements mean. Taking the final arguments toarrayfun首先,我选择了不均匀的输出,因为对于我的函数的每个值,我都计算出输出值的向量,而不是单个值。这将每个输入值的输出列出(在这种情况下,权力), into cells in a cell array.

第一个参数是一个肛门函数,是一个定义的“内联”函数,该函数从工作区中获取其非拨号值。因此,第一个功能,@(p)x.^p,,,,takesXfrom the workspace. The function itself takes the values inX和raises them each to some valuep,函数参数。然后第二个输入到arrayfun,,,,we set the argument to be iterated over to权力从我们的工作区。

最后,由于我们的输出现在位于单元格数组中,在这种情况下,每个单元格包含相等数量的元素,因此我们使用单元格数组转换为数字矩阵Cell2mat

Which of the 2 methods usingarrayfun优选吗?好吧,这很常见,这取决于。由于有一个中间的单元格数组,我们可能希望最大程度地减少其尺寸。向量的典型尺寸有多大X权力? If one is typically substantially larger than the other, we might want to轮廓代码,来自命令行或桌面。剖道师可以帮助我们实现这些权衡。

我再次要求您添加您的想法here。Thanks.

|