【问题标题】:How to multiply a columns in a matrix by a different constant (per column) and then summing each row up in Matlab?如何将矩阵中的列乘以不同的常数(每列),然后在 Matlab 中对每一行求和?
【发布时间】:2014-09-30 19:02:50
【问题描述】:

对于一个项目,我有一定数量的订单进入,我正在尝试计算每个总数的总数。在将矩阵的每一列(每个项目的数量)乘以一个固定常数(每个价格与矩阵中的不同列)之后,我想对每一行中的所有单元格求和,以便我可以找到每行的总价格每个订单。这是我到目前为止的代码:

%A is the matrix of item types and quantities of each item

%A = |OrderNumber  Kitkat   Hershey   Reese's .....  Rolo|
     |  1            3        4        2      .....   4  |
     |  2            4        10       9      .....   2  |
     |  3            7        8        0      .....   0  |
     |.....         ....     ...      ...     ..... .....|

candyPrice = [3 4 3 ........];
orderTotalPrice = {}; 
for i = 1:10
  for k = 2:10
    orderTotalPrice(i) = A(i,k).*candyPrice(k)+orderTotalPrice;        
end
end

我在运行此代码时收到错误消息,提示“未定义函数 'plus' 用于 'cell' 类型的输入参数。”

【问题讨论】:

  • 改用A{i,k}
  • 这不正是矩阵向量积吗?还是我误解了这个问题?如果 A 是矩阵,x 是向量,则 Ax 是 A 的按 x 加权的列的总和。

标签: matlab matrix


【解决方案1】:

问题标题:

"将矩阵中的列乘以不同的常数(每列),然后在 Matlab 中对每一行求和?"

一个符号,* 将执行此操作,(如 cmets 中提到的向量矩阵乘积)

您要计算的内容等同于

orderTotalPrice = candyPrice*matA

其中 candyPrice 是一个 1xn 向量,matA 是 nxm(n 是项目类型的数量,m 是订单的数量......)

对于 OP 的代码

要对单元格 A 使用此方法,我们需要

  • 删除订单号和标题
  • 从单元格转换为矩阵
  • 转置(为 numitemtypes x numorders)

所以执行这一切的单线是:

orderTotalPrice = candyPrice*cell2mat(A(2:end,2:end)).'

有测试数据

A = 

    'orderNo'    'item1'    'item2'    'item3'
    [      1]    [    2]    [    1]    [    3]
    [      2]    [    3]    [    2]    [    3]
    [      3]    [    1]    [    3]    [    3]


candyPrice =

   100    10     1

我们得到

orderTotalPrice = candyPrice*cell2mat(A(2:end,2:end)).'

orderTotalPrice =

   213   323   133

【讨论】:

    【解决方案2】:

    使用p1 = bsxfun(@times,A(:,2:end),candyPrice) 计算所有产品的价格。每个糖果的订单总价为p2 = sum(p1,2),总价为p = sum(p2)


    或者,您可以像这样调整代码:

    candyPrice = [3 4 3 ........];
    orderTotalPrice = zeros(1,10);
    for i = 1:10
        for k = 2:10
            orderTotalPrice(i) = A(i,k).*candyPrice(k)+orderTotalPrice(i);
        end
    end
    total = sum(orderTotalPrice);
    

    【讨论】:

      【解决方案3】:

      首先,orderNumber不能和任何东西相乘,否则没有任何意义。

      因此,我假设size(candyPrice,2) 等于size(A,2)-1

      那么向量化的代码如下:

      orderTotalPrice = sum(repmat(candyPrice,[size(A,1) 1]).*A(:,2:end),2);
      

      【讨论】:

        猜你喜欢
        • 2014-03-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-03-17
        • 1970-01-01
        • 1970-01-01
        • 2012-09-22
        • 1970-01-01
        相关资源
        最近更新 更多