For loop iterations in matlab

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

I am trying to do this using for loops. However, I did not understand this.

This is what I came 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 that I ran into a problem when ii = jj and I have c (0) and this index cannot be used. How can i fix this?

+3
source share
4 answers

Matlab index matrices from 1, so the element c(0)does not exist. The easiest way to fix this is to add 1to your expression, so probably

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

but make sure this does not give you an offside error at the other end of the vector.

, Matlab 1, , , 0. , .

EDIT: @Dan, jj for jj = 1:ii.

+2

:

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

So you need to put in the 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 pseudo code, so you can convert this logic.

+1
source
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
+1
source

All Articles