way to avoid for loops
Afficher commentaires plus anciens
What is the best way to write the following code without using any kind of loop?
N=2;
[x,y]=meshgrid(1:N,1:N);
s=zeros(N);
for i=1:N
for j=1:N
s(i,j)=sum(sum(i*x+j*y));
end
end
Some more: What if I make the function a little complex like below?
N=2;
[x,y]=meshgrid(1:N,1:N);
s=zeros(N);
for i=1:N
for j=1:N
s(i,j)=sum(sum(exp(sqrt((x-i).^2+(y-j).^2));
end
end
Réponses (2)
Roger Stafford
le 14 Juin 2016
Modifié(e) : Roger Stafford
le 14 Juin 2016
If x and y are arbitrarily defined as N-by-N arrays, do this:
[I,J] = ndgrid(1:N);
s = sum(x(:))*I+sum(y(:))*J;
With x and y as you defined them, do this:
s = N^2*(N+1)/2*(x+y);
1 commentaire
Rahul Shaw
le 15 Juin 2016
Roger Stafford
le 15 Juin 2016
This is for your revised problem involving the 'exp' function. (Note: I am assuming the x and y in your code are just as you have written them and not a general x and y.)
N = 10 % <-- You choose N
[I,J] = meshgrid(-N+1:N-1);
T = cumsum(cumsum([zeros(1,2*N);zeros(2*N-1,1),exp(sqrt(I.^2+J.^2))],1),2);
S = T(N+1:2*N,N+1:2*N)-T(N+1:2*N,1:N)-T(1:N,N+1:2*N)+T(1:N,1:N);
Array S is N-by-N with the desired values (except of course for differing rounding errors.)
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!