Use a matrix instead of a for loop
Afficher commentaires plus anciens
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.
Réponses (1)
JESUS DAVID ARIZA ROYETH
le 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)'))));
Catégories
En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!