Reputation: 1513
I'm writing a Matlab function that multiplies the ith element of a vector square by the ith value. I can get the function to work but I would like to not use a for loop. I'd like to use the sum matlab function without a for loop.
%x is the vector
x = [3; 3; 3; 1; 1];
%value = sum(.x^2); I tried this but this wouldn't work as I can't figure out how to get the ith value.
sumvalue = 0;
for i=1:length(x)
fprintf('The j is %d, the value is %d.\n',i, x(i));
sumvalue = sumvalue + (i * x(i)^2);
fprintf('The sumvalue is %d.\n',sumvalue);
end
I've tried a few other things but I can't seem to find or figure out how to get the ith value without using a for loop. I was thinking about using the dot notation on the vector (.x) but I'm not real sure how to use that and then I'm back to the issue of not having the ith value. I'm not new to programming but I'm new to using Matlab. Any help is greatly appreciated.
I've tried the code below. value = sum((1:numel(x)).*x.^2);
but I get the following error, "Error using .* Matrix dimensions must agree.". I've added values to x to show the simple values I'm using. Thanks again for the help.
Upvotes: 0
Views: 1354
Reputation: 112659
To compute the total sum:
sum((1:numel(x)).'.*x(:).^2)
Note that the vector 1:numel(x)
takes the place of your i
but in vectorized form.
If you want all the partial sums:
cumsum((1:numel(x)).'.*x(:).^2)
Upvotes: 2