way to avoid for loops

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

Respuestas (2)

Roger Stafford
Roger Stafford el 14 de Jun. de 2016
Editada: Roger Stafford el 14 de Jun. de 2016

2 votos

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 comentario

Rahul Shaw
Rahul Shaw el 15 de Jun. de 2016
Thanks for your reply but my problem is little more complicated than this. I have updated the question accordingly.

Iniciar sesión para comentar.

Roger Stafford
Roger Stafford el 15 de Jun. de 2016

0 votos

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.)

Categorías

Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.

Productos

Preguntada:

el 14 de Jun. de 2016

Respondida:

el 15 de Jun. de 2016

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by