3
votes

I am trying to solve the following simple problem in matlab: enter image description here

I am trying to do this by using for loops. However, I havent quite figured it out.

This is what I have come up with so far:

n = [0:1:10];
b = 2*n;
c = 0.5*n;

B=0;
for ii = 1:length(b)
    for jj = 1:length(c)
         B(ii) = B+sum(b(jj)*c(ii-jj))
     end
end

It seems like I come into a problem when ii=jj and I have c(0), and this index cannot be used. How can I fix this?

4

4 Answers

7
votes

You are just doing a convolution:

B = conv(b,c);
B = B(1:numel(b)); %// remove unwanted values
2
votes

Matlab indexes arrays from 1, so the element c(0) does not exist. The easiest way to fix this would be to add 1 to your expression, so probably

B(ii) = B+sum(b(jj)*c(ii-jj+1))

but do check that this doesn't give you an off-by-1 error at the other end of the vector.

In general, since Matlab does index from 1, you need to take account of this when translating algorithms from sources, such as your mathematical expression, which index from 0. This is the sort of adjustment one has to make when writing software.

EDIT: as @Dan has commented, you should also revise the loop over jj to for jj = 1:ii.

1
votes

So you need to put a logic as if (ii==jj) B(ii) = B+sum(b(jj)*c(ii-jj+1)) Else B(ii) = B+sum(b(jj)*c(ii-jj)) This is a pseudo code so you can have this logic converted.

1
votes
N = 1:10;
b = 2*N;
c = 0.5*N;

B=zeros(length(N),1);  %//This preallocation of B makes your code much faster

for n = N
    for k = 1:n %//Note the change here
         B(n) = B(n) + b(k)*c(n-k+1);  %// Added the +1 to the index of c like High Performance Mark suggests but also note you don't need the sum() since b(k)*c(n-k+1) is only a single number anyways
    end
end

or even better you can vectorize the inner loop:

for n = N
    B2(n) = b(1:n)*c(n:-1:1)';
end