sherrellbc
sherrellbc

Reputation: 4878

Using Matlab to multiply two vectors using a for-loop

There is a very fundamental Matlab issue that I am missing here. My actual application is much different than this, but the following simplified example outlines the problem I am having.

function [x] = test(y,h)
   x = zeros(1,5);

    for iteration = 1:5
        partialSum = 0;
        for i=1:5, j=1:5;
            partialSum = partialSum + x(i)*h(j);
        end

       x(iteration) = partialSum;
    end

end

Assuming I do not want to vectorize this implementation, how do I properly selectively multiply two aribitrary indices from within two vectors? The above code will throw the following error because partialSum is not an accumulated scalar as I intended it to be.

In an assignment  A(:) = B, the number of elements in A and B must be the same.

Ultimately, what I am trying to do is arbitrarily index into each vector x and y, calculate the scalar result equivalent to the product of the two scalars, and keep a running sum.

Any idea?

Upvotes: 0

Views: 614

Answers (2)

gariepy
gariepy

Reputation: 3674

I think you just need 1 index variable:

for i = 1:5
    partialSum = partialSum + x(i)*h(i);
end

EDIT: If you need i and j to be offset, try this:

offset = 17; % for example
for i = 1:5
    partialSum = partialSum + x(i)*h(i+offset);
end

EDIT2: The most general option

x_indices = [1 2 17 42 900];
h_indices = [3 7 29 401 1000];
for i = 1:5
    partialSum = partialSum + x(x_indices(i))*h(h_indices(i));
end

Upvotes: 3

zeeMonkeez
zeeMonkeez

Reputation: 5177

Try two nested for loops:

for i=1:5
    for j=1:5
        partialSum = partialSum + x(i)*h(j);
    end
end

Your code assigns j=1:5 in every iteration of i. (The first sentence in the Description section of the for manpage describes this usage)

Edit: Incrementing two variables In the case that both variables are to be incremented in the same loop, use one loop adding an offset to i and j (assuming that they can be different). If they are always the same, just use one variable.

i = 1;
j = 1;
for offset=0:4
    partialSum = partialSum + x(i + offset) * h(j + offset);
end

for i=1:5
    partialSum = partialSum + x(i) * h(i);
end

Upvotes: 1

Related Questions