如何编写依赖于其他向量化表达式的向量化表达式? [英] How to code a vectorized expression that depends on other vectorized expression?

查看:76
本文介绍了如何编写依赖于其他向量化表达式的向量化表达式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,如果我有三个表达式:ABC如下:

If for example I have three expressions: A, B and C as follows:

A(i+1) = A(i) + C(i).k
B(i+1) = B(i) + A(i).h
C(i+1) = A(i) + B(i)

其中,kh是一些常数,而mnC的所需大小. i是上一个获得的值,i+1是下一个值.现在,如果使用for循环,则可以将其编码为:

where k and h are some constants and m and n is the desired size of C. i is the previous obtained value, i+1 is the next value. Now, if I use for loop, then I can code it as:

A(1)= 2;
B(1)= 5;
C(1)= 3;
for i=1:10
    A(i+1) = A(i) + C(i)*2;
    B(i+1) = B(i) + A(i)*3;
    C(i+1) = A(i) + B(i);
end

它工作正常.但是我想以 vector形式对其进行编码,就像不必使用循环一样.但是问题是我不知道如何解决以下问题的依赖关系:

And it works just fine. But I want to code it in a vector form, as in without having to use a loop. But the problem is I do not know how to get around the dependency of:

  • A的先前值和先前的C
  • B上的先前值和A上的先前C
  • CAB
  • 的先前值上
  • A on its previous value and previous C value
  • B on it previous values and previous C value of A
  • C on the previous values of A and B

推荐答案

这是一种基于矩阵的方法,用于获取[A;B;C]向量的第n个值.我不会确切地称其为向量化,但这可以为您大大加快速度:

Here's a matrix-based way to obtain the n-th value of the [A;B;C] vector. I wouldn't exactly call it vectorization, but this could speed things up considerably for you:

[A,B,C] = deal(zeros(11,1));
A(1)= 2;
B(1)= 5;
C(1)= 3;

%% // Original method
for k=1:10
  A(k+1) = A(k) + C(k)*2;
  B(k+1) = B(k) + A(k)*3;
  C(k+1) = A(k) + B(k);
end

%% // Matrix method:
%// [ A ]     [1  0  2][ A ]
%// | B |  =  |3  1  0|| B |
%// [ C ]     [1  1  0][ C ]
%//      i+1                i
%// 
%// [ A ]     [1  0  2][ A ]        [1  0  2]   ( [1  0  2][ A ] )
%// | B |  =  |3  1  0|| B |    =   |3  1  0| * ( |3  1  0|| B | )
%// [ C ]     [1  1  0][ C ]        [1  1  0]   ( [1  1  0][ C ] )
%//      i+2                i+1                                 i

%// Thus, this coefficient matrix taken to the n-th power, multiplied by the input 
%// vector will yield the values of A(n+1), B(n+1), and C(n+1):
M = [1 0 2
     3 1 0
     1 1 0];
isequal(M^10*[A(1);B(1);C(1)],[A(11);B(11);C(11)])

实际上,您可以使用M到适当的幂(正或负),以从任何[A,B,C] k 中获得任何[A,B,C] n ...

In reality you can use M to the appropriate power (positive or negative) to obtain any [A,B,C]n from any [A,B,C]k ...

这篇关于如何编写依赖于其他向量化表达式的向量化表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆