# Vectorisation of a simple for loop

1 view (last 30 days)

Show older comments

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.

##### 0 Comments

### Accepted Answer

Thorsten
on 28 Sep 2016

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);

### More Answers (2)

Teja Muppirala
on 28 Sep 2016

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.

KSSV
on 28 Sep 2016

It is very much possible:

https://in.mathworks.com/matlabcentral/answers/81775-recursive-vector-operation-without-for-loops

##### 2 Comments

KSSV
on 28 Sep 2016

### See Also

### Categories

### Community Treasure Hunt

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

Start Hunting!