使用匿名函数而不是循环来总结单元格数组中的值

时间:2022-06-24 21:22:32

I have a matrix called data. It contains 3 columns, company name, company value & company currency, bit like below.

我有一个矩阵叫做数据。它包含3列,公司名称,公司价值和公司货币,如下所示。

  Name      Value      Currency
  ABC       10         USD
  MNO       5          JPY
  PLM       3          USD
  NJK       7          EUR

I need to sum the total value for each currency so my answer would look like below,

我需要对每种货币的总价值进行求和,所以我的答案应该是这样的,

 Currency    Value
 EUR         7
 JPY         5
 USD         13

I know I can do this using a loop but is it possible using an anonymous function and if so how?

我知道我可以用一个循环来做,但是用一个匿名函数可以吗?

Update - Extra information as original post lacked information

更新-额外的信息,因为原始的帖子缺少信息

Below is my solution, which works. However I have seen people use cellFun or anonymous functions and fell like there is a more efficient way (and would to like alternative way) for problems of this nature

下面是我的解决方案,它是有效的。然而,我看到人们使用cellFun或匿名函数,并认为有一种更有效的方法(也希望有另一种方法)来解决这类问题

val     = cell2mat(data(:, 2));              % double - value
sedols  = data(:, [1 3]);                   % cell - name (1st column) and currency (2nd column)

ccy     = unique(sedols(:, 2));
fx_exp  = zeros(length(ccy(:, 1)), 1);

for n = 1 : length(ccy(:, 1))
    index           = strmatch(ccy(n, 1), sedols(:, 2));
    fx_exp(n, 1)    = sum(val(index));
end

1 个解决方案

#1


5  

Using cellfun or arrayfun is not more efficient than a simple loop. To take advantage of vectorization you need to work with pure double arrays.

使用cellfun或arrayfun并不比简单的循环更有效。为了利用矢量化,您需要使用纯双数组。

Assuming your data is stored in a cell array, unique combined with accumarray is the way to go:

假设您的数据存储在一个单元数组中,那么与accumarray结合使用是唯一的:

data = {
    'ABC'   10  'USD'
    'MNO'   5   'JPY'
    'PLM'   3   'USD'
    'NJK'   7   'EUR' };

[a,b,subs] = unique(data(:,3))
vals = [data{:,2}];
currsum = accumarray(subs,vals)
out = [data(b,3) num2cell(currsum)]

out = 

'EUR'    [ 7]
'JPY'    [ 5]
'USD'    [13]

#1


5  

Using cellfun or arrayfun is not more efficient than a simple loop. To take advantage of vectorization you need to work with pure double arrays.

使用cellfun或arrayfun并不比简单的循环更有效。为了利用矢量化,您需要使用纯双数组。

Assuming your data is stored in a cell array, unique combined with accumarray is the way to go:

假设您的数据存储在一个单元数组中,那么与accumarray结合使用是唯一的:

data = {
    'ABC'   10  'USD'
    'MNO'   5   'JPY'
    'PLM'   3   'USD'
    'NJK'   7   'EUR' };

[a,b,subs] = unique(data(:,3))
vals = [data{:,2}];
currsum = accumarray(subs,vals)
out = [data(b,3) num2cell(currsum)]

out = 

'EUR'    [ 7]
'JPY'    [ 5]
'USD'    [13]