Vectorisation of a simple for loop

1 回表示 (過去 30 日間)
David Schranz
David Schranz 2016 年 9 月 28 日
コメント済み: David Schranz 2016 年 9 月 29 日
Will it be possible to write this code vectorised?
x=ones(10,1);
a=zeros(size(x));
b=zeros(size(x));
c=zeros(size(x));
for i = 1:size(x,1)-1
a(i+1) = a(i)+x(i)+b(i);
b(i+1) = b(i)+a(i)+c(i);
c(i+1) = c(i)+b(i)+c(i);
end
Any help would be greatly appreciated.

採用された回答

Thorsten
Thorsten 2016 年 9 月 28 日
A = [1 1 0 0 ; 1 1 1 0 ; 0 1 2 0; 1 0 0 1];
Q = cell2mat(arrayfun(@(i) A^i, 1:9, 'Uni', false));
Q = [zeros(1, 4); reshape(Q(end,:), 4, [])'];
a = Q(:,1); b = Q(:,2); c = Q(:,3);
  1 件のコメント
David Schranz
David Schranz 2016 年 9 月 29 日
Thank you very much for your solution. I would have never figured that out.

サインインしてコメントする。

その他の回答 (2 件)

Teja Muppirala
Teja Muppirala 2016 年 9 月 28 日
Just wondering, but what is your purpose in vectorizing that code? If it's to make it faster, I don't think you can do much better than what you've already got, especially if you have a recent version of MATLAB.
If it's to make it more readable, or more general (flexibly deal with more variables), so you don't have to keep writing every letter like this
a(i+1)=...
b(i+1)=...
c(i+1)=...
d(i+1)= ...
...
then you could use matrix equations.
x=ones(10,1); % External input
A = [1 1 0; 1 1 1; 0 1 2]; % State matrix
B = [1;0;0]; % Input matrix
v = zeros(length(B),length(x)); % v contains [a,b,c]
for i = 1:size(x,1)-1
v(:,i+1) = A*v(:,i) + B*x(i);
end
For many applications, matrix representation is usually how this type of calculation is expressed.
  1 件のコメント
David Schranz
David Schranz 2016 年 9 月 29 日
Yes, I try to make things faster. And yes it looks like the vectorised version is not faster. Nevertheless your code helped me to understand the solution provided by Thorsten. Also I consider using your code sample to flexibly deal with more variables. Thank you very much for your answer.

サインインしてコメントする。


KSSV
KSSV 2016 年 9 月 28 日
It is very much possible:
https://in.mathworks.com/matlabcentral/answers/81775-recursive-vector-operation-without-for-loops
  2 件のコメント
Stephen23
Stephen23 2016 年 9 月 28 日
編集済み: Stephen23 2016 年 9 月 28 日
@Dr. Siva Srinivas Kolukula: the solution presented in that answer, and indeed the filter command itself, is a fundamentally 1D solution, even if applied to an array. The question above has dependencies between the variables a, b, and c. How do you propose to represent these using a 1D filter?
KSSV
KSSV 2016 年 9 月 28 日
If I am not mistaken, a similar question appeared a week ago which was vectorised using filter...I searched for the question, but could not get it.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeMatrices and Arrays についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by