我需要对矩阵的列应用函数。假设我有这个矩阵 -
>> m = rand(3,3)
m =
0.8626 0.5661 0.8489
0.6830 0.1498 0.1401
0.0857 0.4775 0.3296
以及两个下限和上限向量--
>> mins = [2 3 5]
mins =
2 3 5
>> maxs = [7 11 13]
maxs =
7 11 13
现在我正在做的是将矩阵分成列 -
>> cols = num2cell(m, 1)
cols =
[3x1 double] [3x1 double] [3x1 double]
现在我尝试的是在每列上应用一个函数,该函数采用下限和上限来规范化列值,更具体地说我想规范化列m(:,1)
与 mins(1)
和 maxs(1)
,m(:,2)
与 mins(2)
和 maxs(2)
... 列 m(:,n)
以及 mins(n)
和 maxs (n)
等等。我的看法是这样的——
>> norm_cols = cellfun(@(c, lb, ub) (ub - lb) .* c + lb, cols, mins, maxs);
Error using cellfun
Input #3 expected to be a cell array, was double instead.
我的问题是这样的事情在matlab中可行吗?假设这是可行的,那么如何将分割的列再次合并到矩阵中?
此外,请注意,我知道循环,但我不想使用它(因为我的矩阵可以增长到 1000x1000),所以请不要提供任何使用循环的解决方案。虽然我不确定函数映射是否可以比循环提供更好的速度(这是另一个问题,但不是今天)。
最佳答案
嗯,你当然可以做这样的事情
>> x = {[1; 2; 3]/10, [4; 5; 6]/10, [7; 8; 9]/10};
>> mins = {1.5 4.5 7.5};
>> maxs = {2.5 5.5 8.5};
>> y = cellfun(@(a, lb, ub) (ub-lb) * x + lb, x, mins, maxs, 'uniform', 0)
y =
[3x1 double] [3x1 double] [3x1 double]
>> [y{:}]
ans =
1.600000000000000 4.900000000000000 8.199999999999999
1.700000000000000 5.000000000000000 8.300000000000001
1.800000000000000 5.100000000000000 8.400000000000000
但使用 bsxfun
跨行广播参数甚至更酷,而无需先将其转换为元胞数组
>> x = [1 4 7; 2 5 8; 3 6 9] / 10;
>> mins = [1.5 4.5 7.5];
>> maxs = [2.5 5.5 8.5];
>> y = bsxfun(@plus, bsxfun(@times, x, maxs-mins), mins);
关于matlab:列上的映射函数(如 lisp),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28932747/