Use a matrix instead of a for loop
8 views (last 30 days)
Show older comments
I'm trying to condense my code. I currently have this for loop in my code
N = 100
x = 1:N
p = 6;
sum_x = zeros([p+1,1]);
for k=0:p
sum_x(k+1) = dot(x(1:N-k),x(1+k:N));
end
This gives me the output I want, a matrix containing the sum of each dot product for k = 0:p.
I want to condense it using matrices in a way like this:
k = 0:p
sum_x = dot(x(1:N-k),x(1+k:N));
However MATLAB takes k's first value and ignores the rest, giving me a scalar output.
I've been playing around with the code for a while now and can't seem to get the solution I want this way. Please answer if you know how to get it.
0 Comments
Answers (1)
JESUS DAVID ARIZA ROYETH
on 10 Nov 2019
solution:
N = 100;
x = 1:N;
p = 6;
xx=repmat(x,p+1,1);
sum_x=diag(fliplr(triu(fliplr(xx)))*rot90(triu(fliplr(xx+(0:p)'))));
0 Comments
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!