【问题标题】:Matlab multiple matrix rowwise based on rule基于规则的Matlab多矩阵逐行
【发布时间】:2017-05-23 18:52:13
【问题描述】:

我有这个矩阵

mp=
2
5
8


fp=
0.67   0.34   0
0.34   0.34   0.34
0      0.5    0.5

还有这个矩阵

t=
1
1
1
2
3
2
3

使用这条规则:

  • 如果 t=1 则输出 = mp*(fp 第一行)
  • 如果 t=2 则输出 = mp*(fp 2nd row)
  • 如果 t=3 则输出 = mp*(fp 第 3 行)

所以输出应该是这样的:

output=
3
3
3
5
6,5
5
6,5

我正在尝试使用此代码 但输出==t

[o p]=size(t)
[q r]=size(mp)
for i=1:o;
    j=1:q;

    if t(i)==j
        output=mp*fp(j,:)
    else
        output=t(i)
    end
end

【问题讨论】:

    标签: matlab row


    【解决方案1】:

    单线解决方案

    您可以使用以下语法:

    output = sum(repmat(mp,1,length(t))'.*fp(t,:),2)
    

    结果

    ans =
    3.0400
    3.0400
    3.0400
    5.1000
    6.5000
    5.1000
    6.5000
    

    示例

    %variables declaration
    fp= [0.67   0.34   0; 0.34   0.34   0.34;0      0.5    0.5];
    mp = [2; 5; 8]
    t = [1,1,1,2,3,2,3]
    
    %calculates result
    output = sum(repmat(mp,1,length(t))'.*fp(t,:),2)
    

    【讨论】:

    • 如果存在不在 t 中的值怎么办? Fo example t=4 它不在 mp 或 fp 中?
    【解决方案2】:

    由于您的 t 值已经是行号,您可以直接使用 t 值进行乘法运算。

    mp=[2
    5
    8] ;
    
    fp=[0.67   0.34   0
    0.34   0.34   0.34
    0      0.5    0.5] ;
    t=[1
    1
    1
    2
    3
    2
    3] ;
    
    iwant = cell(size(t)) ;  % initilaize the required data 
    
    for i = 1:length(t)    % loop for each value of _t_
        iwant{i} = mp*fp(t(i),:) ;
    end
    

    【讨论】:

    • 我得到了这个输出 [3x3 double] [3x3 double] [3x3 double] [3x3 double] [3x3 double] [3x3 double] [3x3 double]
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-16
    • 1970-01-01
    • 2015-01-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多